<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<meta charset="utf-8">
		<title>AppKubos</title>
		<link rel="author" href="https://plus.google.com/111999105737049483944">
		<link rel="author" href="http://appkubos.com/pujan">
		<!-- CSS -->
		<link rel="stylesheet" href="AppKubos_files/style.css" type="text/css" media="screen">
		<link rel="stylesheet" href="AppKubos_files/social-icons.css" type="text/css" media="screen">
		<link rel="icon" href="http://appkubos.com/images/icon.png" type="image/png">
		<!--[if IE 8]>
			<link rel="stylesheet" type="text/css" media="screen" href="/css/ie8-hacks.css" />
		<![endif]-->
		<!-- ENDS CSS -->	

		<!-- GOOGLE FONTS -->
		<!-- link href='http://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet' type='text/css'>
		<link href='http://fonts.googleapis.com/css?family=PT+Mono|Stint+Ultra+Expanded|Armata' rel="stylesheet" type="text/css" -->
								<script type="text/javascript" src="AppKubos_files/shCore.js"></script>
		<script type="text/javascript" src="AppKubos_files/shBrushJScript.js"></script>
		<script type="text/javascript" src="AppKubos_files/shBrushJava.js"></script>
		<script type="text/javascript" src="AppKubos_files/shBrushBash.js"></script>
		<link type="text/css" rel="stylesheet" href="AppKubos_files/shCoreDefault.css">
		<script type="text/javascript">SyntaxHighlighter.all();</script>
		<link href="AppKubos_files/shThemeEmacs.css" rel="stylesheet" type="text/css">


		<!-- JS -->
		<script type="text/javascript" src="AppKubos_files/jquery-1.js"></script>
		<script type="text/javascript" src="AppKubos_files/jquery-ui-1.js"></script>
		<script type="text/javascript" src="AppKubos_files/easing.js"></script>
		<script type="text/javascript" src="AppKubos_files/jquery_003.js"></script>
		<script type="text/javascript" src="AppKubos_files/quicksand.js"></script>
		<script type="text/javascript" src="AppKubos_files/jquery_007.js"></script>
		<script type="text/javascript" src="AppKubos_files/custom.js"></script>
        <script type="text/javascript" src="AppKubos_files/pujan.js"></script>
		
        <script type="text/javascript" src="AppKubos_files/jquery.js"></script>
  		<script>
    		$(window).load(function(){
      		$("#menu-sticky").sticky({ topSpacing: 0 });
    	});
  		</script>




		<!--[if IE]>
			<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->
		
		<!--[if IE 6]>
			<script type="text/javascript" src="js/DD_belatedPNG.js"></script>
			<script>
	      		/* EXAMPLE */
	      		//DD_belatedPNG.fix('*');
	    	</script>
		<![endif]-->
		<!-- ENDS JS -->
		
		
		<!-- Nivo slider -->
		<link rel="stylesheet" href="AppKubos_files/nivo-slider.css" type="text/css" media="screen">
		<script src="AppKubos_files/jquery_005.js" type="text/javascript"></script>
		<!-- ENDS Nivo slider -->
		
		<!-- tabs -->
		<link rel="stylesheet" href="AppKubos_files/tabs.css" type="text/css" media="screen">
		<script type="text/javascript" src="AppKubos_files/tabs.js"></script>
  		<!-- ENDS tabs -->
  		
  		<!-- prettyPhoto -->
		<script type="text/javascript" src="AppKubos_files/jquery_002.js"></script>
		<link rel="stylesheet" href="AppKubos_files/prettyPhoto.css" type="text/css" media="screen">
		<!-- ENDS prettyPhoto -->
		
		<!-- superfish -->
		<link rel="stylesheet" media="screen" href="AppKubos_files/superfish.css"> 
		<!-- link rel="stylesheet" media="screen" href="/ajax2/css/superfish-left.css" / --> 
		<script type="text/javascript" src="AppKubos_files/hoverIntent.js"></script>
		<script type="text/javascript" src="AppKubos_files/superfish.js"></script>
		<script type="text/javascript" src="AppKubos_files/supersubs.js"></script>
		<!-- ENDS superfish -->
		
		<!-- poshytip -->
		<link rel="stylesheet" href="AppKubos_files/tip-twitter.css" type="text/css">
		<link rel="stylesheet" href="AppKubos_files/tip-yellowsimple.css" type="text/css">
		<script type="text/javascript" src="AppKubos_files/jquery_004.js"></script>
		<!-- ENDS poshytip -->
		
		<!-- Tweet -->
		<!-- link rel="stylesheet" href="/ajax2/css/jquery.tweet.css" media="all"  type="text/css"/> 
		<script src="/ajax2/js/tweet/jquery.tweet.js" type="text/javascript"></script --> 
		<!-- ENDS Tweet -->
		
		<!-- Fancybox -->
		<link rel="stylesheet" href="AppKubos_files/jquery.css" type="text/css" media="screen">
		<script type="text/javascript" src="AppKubos_files/jquery_006.js"></script>
		<!-- ENDS Fancybox -->
		
		<!-- SKIN -->
		<link rel="stylesheet" href="AppKubos_files/style_002.css" type="text/css" media="screen">

	<style id="poshytip-css-tip-twitter" type="text/css">div.tip-twitter{visibility:hidden;position:absolute;top:0;left:0;}div.tip-twitter table, div.tip-twitter td{margin:0;font-family:inherit;font-size:inherit;font-weight:inherit;font-style:inherit;font-variant:inherit;}div.tip-twitter td.tip-bg-image span{display:block;font:1px/1px sans-serif;height:10px;width:10px;overflow:hidden;}div.tip-twitter td.tip-right{background-position:100% 0;}div.tip-twitter td.tip-bottom{background-position:100% 100%;}div.tip-twitter td.tip-left{background-position:0 100%;}div.tip-twitter div.tip-inner{background-position:-10px -10px;}div.tip-twitter div.tip-arrow{visibility:hidden;position:absolute;overflow:hidden;font:1px/1px sans-serif;}</style><style id="poshytip-css-tip-yellowsimple" type="text/css">div.tip-yellowsimple{visibility:hidden;position:absolute;top:0;left:0;}div.tip-yellowsimple table, div.tip-yellowsimple td{margin:0;font-family:inherit;font-size:inherit;font-weight:inherit;font-style:inherit;font-variant:inherit;}div.tip-yellowsimple td.tip-bg-image span{display:block;font:1px/1px sans-serif;height:10px;width:10px;overflow:hidden;}div.tip-yellowsimple td.tip-right{background-position:100% 0;}div.tip-yellowsimple td.tip-bottom{background-position:100% 100%;}div.tip-yellowsimple td.tip-left{background-position:0 100%;}div.tip-yellowsimple div.tip-inner{background-position:-10px -10px;}div.tip-yellowsimple div.tip-arrow{visibility:hidden;position:absolute;overflow:hidden;font:1px/1px sans-serif;}</style><script>try {  for(var lastpass_iter=0; lastpass_iter < document.forms.length; lastpass_iter++){    var lastpass_f = document.forms[lastpass_iter];    if(typeof(lastpass_f.lpsubmitorig)=="undefined"){      if (typeof(lastpass_f.submit) == "function") {        lastpass_f.lpsubmitorig = lastpass_f.submit;        lastpass_f.submit = function(){          var form = this;          try {            if (document.documentElement && 'createEvent' in document)            {              var forms = document.getElementsByTagName('form');              for (var i=0 ; i<forms.length ; ++i)                if (forms[i]==form)                {                  var element = document.createElement('lpformsubmitdataelement');                  element.setAttribute('formnum',i);                  element.setAttribute('from','submithook');                  document.documentElement.appendChild(element);                  var evt = document.createEvent('Events');                  evt.initEvent('lpformsubmit',true,false);                  element.dispatchEvent(evt);                  break;                }            }          } catch (e) {}          try {            form.lpsubmitorig();          } catch (e) {}        }      }    }  }} catch (e) {}</script></head>
	
	<body class="">
	
	<article>
	<!-- WRAPPER -->
	<div id="wrapper">
		
		<!-- HEADER -->
		<div id="header">
			<a href="http://appkubos.com/"><img id="logo" src="AppKubos_files/logo2.png" alt="appkubos" height="80" width="128"></a>
			<!-- Social -->
			<div id="social-holder">
			<ul class="social">
<li><a href="http://gplus.to/pujansrt" class="poshytip google" title="Google+"></a></li>
<li><a href="http://www.facebook.com/pujansrt" class="poshytip facebook" title="Facebook"></a></li>
<li><a href="http://www.twitter.com/pujansrt" class="poshytip twitter" title="Follow tweets"></a></li>
<li><a href="http://appkubos.com/1-gallery.php" class="poshytip picasa" title="Gallery"></a></li>
<!-- <li><a href="http://picasaweb.google.com/pujansrt" class="poshytip picasa" title="Gallery"></a></li> -->
<li><a href="http://pujansrt.blogspot.com/" class="poshytip blogger" title="Blogger"></a></li>
<!--
<li><a href="http://www.addthis.com" class="poshytip addthis" title="Tell everybody"></a></li>
<li><a href="http://www.youtube.com" class="poshytip youtube" title="View our videos"></a></li>
-->
</ul>
			</div>
			<!-- ENDS Social -->
			
			<!-- Navigation -->
			

			<div style="height: 0px;" class="sticky-wrapper is-sticky" id="menu-sticky-sticky-wrapper"><div style="position: fixed; top: 0px;" id="menu-sticky">

			<ul id="nav" class="sf-menu sf-js-enabled sf-shadow">
				<li id="home"><a href="http://appkubos.com/" class="homeIcon sf-with-ul">Home<span class="sf-sub-indicator"> »</span></a>
					<ul style="display: none; visibility: hidden;">
						<li><a href="http://appkubos.com/pujan/"><span> Pujan</span></a></li>
						<li><a href="http://appkubos.com/contact/">Contact</a></li>
					</ul>
				</li>
                <li><a href="http://appkubos.com/python/">Python</a></li>                
                <li><a href="http://appkubos.com/java/">Java</a></li>
                <li><a href="http://appkubos.com/mac/">&nbsp; Mac &nbsp; </a></li>
                <li><a href="http://appkubos.com/linux/">Linux</a></li>
				<li><a href="http://appkubos.com/bash/">Bash</a></li>   
                <li><a href="http://appkubos.com/network/">Network</a></li>
                <li><a href="http://appkubos.com/web/">Tools</a></li>             
                <li><a href="http://appkubos.com/web/SearchFull/">Search</a></li>
                              
                
            	<li><a href="http://appkubos.com/login.php">
            		Login</a>
				</li>
				
			</ul>
			
			<!-- Navigation -->	
			<!-- ENDS Sticky -->
			</div></div>
			
			<!-- search -->
			<div class="top-search">
				<form name="myform2" method="get" id="searchform" action="#">
					<div>
						<input class="headsearch" value="Search..." name="mytextfield2" id="s" onfocus="defaultInput(this)" onblur="clearInput(this)" onkeyup="showResult(this.value)" type="text">
						<input id="searchsubmit" value=" " type="submit"><div class="searchbox" id="livesearch"></div>
					</div>
				</form>
			</div>
			<!-- ENDS search -->
			

			

		</div>
		<!-- ENDS HEADER -->
		
	<div id="main">
			
			<!-- content -->
			<div id="content">
				


<script type="text/javascript">
function showResult(str)
{
if (str.length==0)
  { 
  document.getElementById("livesearch").innerHTML="";
  document.getElementById("livesearch").style.border="0px";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
xmlhttp.open("GET","/livesearch.php?q="+str,true);
xmlhttp.send();



}
</script><div id="content">
<div id="welcome" style="text-align:justify;">
<h3>Java IO.</h3><br>

<p>Programming simple I/O operations is easy, which  involves only a few
 classes and methods. You could do it by looking at a few samples. 
Programming efficient, portable I/O is extremely difficult, especially 
if you have to deal with different character sets. This explains why 
there are so many I/O packages (nine in JDK 1.7)!</p>

<p>JDK has two sets of I/O packages:</p>
<ol>
<li>the Standard I/O (in package <code>java.io</code>), introduced since JDK 1.0 for stream-based I/O, and</li>
<li>the New I/O (in packages <code>java.nio</code>), introduced in JDK 1.4, for more efficient buffer-based I/O.</li>
</ol>

<p>JDK 1.5 introduces the formatted text-I/O via new classes <code>java.util.Scanner</code> and <code>Formatter</code>, and C-like <code>printf()</code> and <code>format()</code> methods for formatted output using format specifiers.</p>
<p> JDK 1.7  enhances supports for file I/O via the so-called NIO.2 (non-blocking I/O) in new package <code>java.nio.file</code> and its auxiliary packages. It also introduces a new <code>try</code>-with-resources syntax to simplify the coding of <code>close()</code> method.</p>

<h3>File and Directory</h3>

<h4>Class <code>java.io.File</code> (Pre-JDK 7)</h4>

<p>The class <code>java.io.File</code> can represent either a file or a directory. [JDK 1.7 introduces a more versatile <code>java.nio.file.Path</code>, which  overcomes many limitations of <code>java.io.File</code>.]</p>

<p>A path string is used to locate a file or a directory. Unfortunately, path strings are system dependent, e.g., "<code>c:\myproject\java\Hello.java</code>" in Windows or "<code>/myproject/java/Hello.java</code>" in Unix/Mac.</p>

<ul>
<li>Windows use back-slash <code>'\'</code> as the directory separator; while Unixes/Mac use forward-slash <code>'/'</code>.</li>
<li>Windows use semi-colon <code>';'</code> as path separator to separate a list of paths; while Unixes/Mac use colon <code>':'</code>.</li>
<li>Windows use "<code>\r\n</code>" as line delimiter for text file; while Unixes use "<code>\n</code>" and Mac uses "<code>\r</code>".</li>
<li>The "<code>c:\</code>" or "<code>\</code>" is called the root. Windows supports multiple roots, each maps to a drive (e.g., "<code>c:\</code>", "<code>d:\</code>"). Unixes/Mac has a single root ("<code>\</code>").</li>
</ul>
<p> A path could be absolute (beginning from the root) or relative 
(which is relative to a reference directory). Special notations "<code>.</code>" and "<code>..</code>" denote the current directory and the parent directory, respectively.</p>

<p>The <code>java.io.File</code> class maintains these system-dependent properties, for you to write programs that are portable:</p>
<ul>
<li>Directory Separator: in <code>static</code> fields <code>File.separator</code> (as <code>String</code>) and <code>File.separatorChar</code>. [They failed to follow the  Java naming convention for constants adopted since JDK 1.2.] As mentioned, Windows use backslash <code>'\'</code>; while Unixes/Mac use forward slash <code>'/'</code>.</li>
<li>Path Separator: in <code>static</code> fields <code>File.pathSeparator</code> (as <code>String</code>) and <code>File.pathSeparatorChar</code>. As mentioned, Windows use semi-colon <code>';'</code> to separate a list of paths; while Unixes/Mac use colon <code>':'</code>.</li>
</ul>

<p>You can construct a <code>File</code> instance with a path string or 
URI, as follows. Take note that the physical file/directory may or may 
not exist. A file URL takes the form of <code>file://...</code>, e.g., <code>file:///d:/docs/programming/java/test.html</code>.</p>
<div><div id="highlighter_377768" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java plain">File(String pathString)</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">File(String parent, String child)</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java plain">File(File parent, String child)</code></div><div class="line number4 index3 alt1"><code class="java comments">//# Constructs a File instance based on the given path string.</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;</code>&nbsp;</div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java plain">File</code></div><div class="line number7 index6 alt2"><code class="java comments">// Constructs a File instance by converting from the given file-URI "<a href="file:///">file://....</a>"</code></div></div></td></tr></tbody></table></div></div>

<p>For examples,</p>
<div><div id="highlighter_417281" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">File file = </code><code class="java keyword">new</code> <code class="java plain">File(</code><code class="java string">"in.txt"</code><code class="java plain">);&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# A file relative to the current working directory</code></div><div class="line number2 index1 alt1"><code class="java plain">File file = </code><code class="java keyword">new</code> <code class="java plain">File(</code><code class="java string">"d:\\myproject\\java\\Hello.java"</code><code class="java plain">);&nbsp; </code><code class="java comments">//# A file with absolute path</code></div><div class="line number3 index2 alt2"><code class="java plain">File dir&nbsp; = </code><code class="java keyword">new</code> <code class="java plain">File(</code><code class="java string">"c:\\temp"</code><code class="java plain">);&nbsp;&nbsp; </code><code class="java comments">//# A directory</code></div></div></td></tr></tbody></table></div></div>

<p>For applications that you intend to distribute as JAR files, you should use the <code>URL</code> class to reference the resources, as it can reference disk files as well as JAR'ed files , for example,</p>
<div><div id="highlighter_310239" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">java.net.URL url = </code><code class="java keyword">this</code><code class="java plain">.getClass().getResource(</code><code class="java string">"icon."</code><code class="java plain">);</code></div></div></td></tr></tbody></table></div></div>

<h5>Verifying Properties of a File/Directory</h5>
<div><div id="highlighter_343342" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">exists()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">// Tests if this file/directory exists.</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">long</code> <code class="java plain">length()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">// Returns the length of this file.</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">isDirectory()&nbsp; </code><code class="java comments">//# Tests if this instance is a directory.</code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">isFile()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Tests if this instance is a file.</code></div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">canRead()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Tests if this file is readable.</code></div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">canWrite()&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Tests if this file is writable.</code></div><div class="line number7 index6 alt2"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">delete()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Deletes this file/directory.</code></div><div class="line number8 index7 alt1"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">deleteOnExit()&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Deletes this file/directory when the program terminates.</code></div><div class="line number9 index8 alt2"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">renameTo(File dest) </code><code class="java comments">//# Renames this file.</code></div><div class="line number10 index9 alt1"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">mkdir()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Makes (Creates) this directory.</code></div></div></td></tr></tbody></table></div></div>

<h5>List Directory</h5>
<p>For a directory, you can use the following methods to list its contents:</p>
<div><div id="highlighter_675317" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java plain">String[] list()&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# List the contents of this directory in a String-array</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">File[] listFiles()&nbsp; </code><code class="java comments">//# List the contents of this directory in a File-array</code></div></div></td></tr></tbody></table></div></div>

<p>Example: The following program recursively lists the contents of a given directory (similar to Unix's <code>"ls -r"</code> command).</p>
<div><div id="highlighter_757258" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# Recursively list the contents of a directory (Unix's "ls -r" command).</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.io.File;</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">ListDirectoryRecusive {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">File dir = </code><code class="java keyword">new</code> <code class="java plain">File(</code><code class="java string">"d:\\myproject\\test"</code><code class="java plain">);&nbsp; </code><code class="java comments">//# Escape sequence needed for '\'</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">listRecursive(dir);</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code>&nbsp;</div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">listRecursive(File dir) {</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(dir.isDirectory()) {</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">File[] items = dir.listFiles();</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(File item : items) {</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(item.getAbsoluteFile());</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(item.isDirectory()) listRecursive(item);&nbsp; </code><code class="java comments">//# Recursive call</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number18 index17 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<h5>(Advanced) List Directory with Filter</h5>
<p>You can apply a filter to <code>list()</code> and <code>listFiles()</code>, to list only files that meet a certain criteria.</p>
<div><div id="highlighter_921856" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java plain">String[] list(FilenameFilter filter)</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">File[] listFiles(FilenameFilter filter)</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java plain">File[] listFiles(FileFilter filter)</code></div></div></td></tr></tbody></table></div></div>

<p>The <code>interface</code> <code>java.io.FilenameFilter</code> declares one <code>abstract</code> method:</p>
<div><div id="highlighter_203937" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">accept(File dirName, String fileName)</code></div></div></td></tr></tbody></table></div></div>
<p>The <code>list()</code> and <code>listFiles()</code> methods does a call-back to <code>accept()</code> for each of the file/sub-directory produced.  You can program your filtering criteria in <code>accept()</code>.  Those files/sub-directories that result in a <code>false</code> return will be excluded.</p>
<p>Example: The following program lists only files that meet a certain filtering criteria.</p>

<div><div id="highlighter_675246" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# List files that end with ".java"</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.io.File;</code></div><div class="line number3 index2 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.FilenameFilter;</code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">ListDirectoryWithFilter {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">File dir = </code><code class="java keyword">new</code> <code class="java plain">File(</code><code class="java string">"."</code><code class="java plain">);&nbsp;&nbsp; </code><code class="java comments">//# current working directory</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(dir.isDirectory()) {</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# List only files that meet the filtering criteria</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//&nbsp; programmed in accept() method of FilenameFilter.</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String[] files = dir.list(</code><code class="java keyword">new</code> <code class="java plain">FilenameFilter() {</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">accept(File dir, String file) {</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">return</code> <code class="java plain">file.endsWith(</code><code class="java string">".java"</code><code class="java plain">);</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">});&nbsp; </code><code class="java comments">//# an anonymous inner class as FilenameFilter</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(String file : files) {</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(file);</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number20 index19 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<h4>Class <code>java.nio.file.Path</code> (JDK 7)</h4>
<p>Read "<a href="http:///#jdk7io">File I/O in JDK 1.7</a>".</p>

<h3>Stream I/O in Standard I/O (<span class="font-code">java.io Package)</span></h3>

<p>Programs read inputs from data sources (e.g., keyboard, file, 
network, memory buffer, or another program) and write outputs to data 
sinks (e.g., display console, file, network, memory buffer, or another 
program).  In Java standard I/O, inputs and outputs are handled by the 
so-called streams. A stream is a sequential and contiguous one-way flow 
of data (just like water or oil flows through the pipe).  It is 
important to mention that Java does not differentiate between the 
various types of data sources or sinks (e.g., file or network) in stream
 I/O.  They are all treated as a sequential flow of data.  Input and 
output streams can be established from/to any data source/sink, such as 
files, network, keyboard/console or another program.  The Java program 
receives data from a source by opening an input stream, and sends data 
to a sink by opening an output stream.

All Java I/O streams are one-way (except the <code>RandomAccessFile</code>,
 which will be discussed later).  If your program needs to perform both 
input and output, you have to open two  streams - an input stream and an
 output stream. </p>

<p>Stream I/O operations involve three steps:</p>
<ol>
<li>Open an input/output stream associated with a physical device (e.g.,
 file, network, console/keyboard), by constructing an appropriate I/O 
stream instance.</li>
<li>Read from the opened input stream until "end-of-stream" encountered,
 or write to the opened output stream (and optionally flush the buffered
 output).</li>
<li>Close the input/output stream.</li>
</ol>

<p>Java's I/O operations is more complicated than C/C++ to support internationalization (i18n). Java internally stores characters (<code>char</code>
 type) in 16-bit UCS-2 character set. But the external data source/sink 
could store characters in other character set (e.g., US-ASCII, 
ISO-8859-x, UTF-8, UTF-16, and many others), in fixed length of 8-bit or
 16-bit, or in variable length of 1 to 4 bytes. [Read "<a href="http://appkubos.com/java/DataRepresentation.html//#charencoding">Character Sets and Encoding Schemes</a>"].
 As a consequence, Java needs to differentiate between byte-based I/O 
for processing raw bytes or binary data, and character-based I/O for 
processing texts made up of characters.</p>

<img class="image-center" src="AppKubos_files/IO_StreamVsCharacter.png">

<h3>Byte-Based I/O &amp; Byte Streams</h3>

<img class="image-center" src="AppKubos_files/IO_InputOutputStreams.png">

<p>Byte streams are used to read/write raw bytes serially from/to an external device. All the byte streams are derived from the <code>abstract</code> superclasses <code>InputStream</code> and <code>OutputStream</code>, as illustrated in the  class diagram.</p>

<h4>Reading from an <span class="font-code">InputStream</span></h4>
<p>The <code>abstract</code> superclass <code>InputStream</code> declares an <code>abstract</code> method <code>read()</code> to read one data-byte from the input source:</p>

<div><div id="highlighter_373880" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">abstract</code> <code class="java keyword">int</code> <code class="java plain">read() </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<p> The <code>read()</code> method:</p>
<ul>
<li>returns the input byte read as an <code>int</code> in the range of 0 to 255, or</li>
<li>returns -1 if "end of stream" condition is detected, or</li>
<li>throws an <code>IOException</code> if it encounters an I/O error.</li>
</ul>

<p>The <code>read()</code> method returns an <code>int</code> instead of a <code>byte</code>, because it uses -1 to indicate end-of-stream.</p>
<p>The <code>read()</code> method  blocks until a byte is available, an 
I/O error occurs, or the "end-of-stream" is detected.  The term "block" 
means that the method (and the program) will be suspended. The program 
will resume only when the method returns.</p>

<p>Two variations of <code>read()</code> methods are implemented in the <code>InputStream</code> for reading a block of bytes into a byte-array. It returns the number of bytes read, or -1 if "end-of-stream" encounters.</p>
<div><div id="highlighter_910231" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">read(</code><code class="java keyword">byte</code><code class="java plain">[] bytes, </code><code class="java keyword">int</code> <code class="java plain">offset, </code><code class="java keyword">int</code> <code class="java plain">length) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java comments">//# Read "length" number of bytes, store in bytes array starting from offset of index.</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">read(</code><code class="java keyword">byte</code><code class="java plain">[] bytes) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number4 index3 alt1"><code class="java comments">//# Same as read(bytes, 0, bytes.length)</code></div></div></td></tr></tbody></table></div></div>

<h4>Writing to an <span class="font-code">OutputStream</span></h4>

<p>Similar to the input counterpart, the <code>abstract</code> superclass <code>OutputStream</code> 
 declares an abstract method <code>write()</code> to write a data-byte to the output sink. <code>write()</code> takes an <code>int</code>. The least-significant byte of the <code>int</code> argument is written out;  the upper 3 bytes are discarded. It throws an <code>IOException</code> if I/O error occurs (e.g., output stream has been closed).</p>
 
<div><div id="highlighter_459214" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java keyword">abstract</code> <code class="java keyword">void</code> <code class="java plain">write(</code><code class="java keyword">int</code> <code class="java plain">unsignedByte) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<p>Similar to the <code>read()</code>, two variations of the <code>write()</code> method to write a block of bytes from a byte-array are implemented:</p>

<div><div id="highlighter_418726" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">write(</code><code class="java keyword">byte</code><code class="java plain">[] bytes, </code><code class="java keyword">int</code> <code class="java plain">offset, </code><code class="java keyword">int</code> <code class="java plain">length) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java comments">//# Write "length" number of bytes, from the bytes array starting from offset of index.</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">write(</code><code class="java keyword">byte</code><code class="java plain">[] bytes) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number4 index3 alt1"><code class="java comments">//# Same as write(bytes, 0, bytes.length)</code></div></div></td></tr></tbody></table></div></div>

<h4>Opening &amp; Closing I/O Streams</h4>

<p>You open an I/O stream by constructing an instance of the stream. Both the <code>InputStream</code> and the <code>OutputStream</code> provides  a <code>close()</code> method to close the stream, which performs the necessary clean-up operations to free up the system resources.</p>

<div><div id="highlighter_755836" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">close() </code><code class="java keyword">throws</code> <code class="java plain">IOException&nbsp; </code><code class="java comments">//# close this Stream</code></div></div></td></tr></tbody></table></div></div>

<p> It is a good practice to explicitly close the I/O stream, by running <code>close()</code> in the <code>finally</code> clause of <code>try-catch-finally</code>
 to free up the system resources immediately when the stream is no 
longer needed. This could prevent serious resource leaks. Unfortunately,
 the <code>close()</code> method also throws a <code>IOException</code>, and needs to be enclosed in a nested <code>try-catch</code> statement, as follows. This makes the codes somehow ugly.</p>

<div><div id="highlighter_28928" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">FileInputStream in = </code><code class="java keyword">null</code><code class="java plain">;</code></div><div class="line number2 index1 alt1"><code class="java plain">......&nbsp; </code></div><div class="line number3 index2 alt2"><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">in = </code><code class="java keyword">new</code> <code class="java plain">FileInputStream(...);&nbsp; </code><code class="java comments">//# Open stream</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">......</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">......</code></div><div class="line number7 index6 alt2"><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number9 index8 alt2"><code class="java plain">} </code><code class="java keyword">finally</code> <code class="java plain">{&nbsp; </code><code class="java comments">//# always close the I/O streams</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(in != </code><code class="java keyword">null</code><code class="java plain">) in.close();</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number15 index14 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<p> JDK 1.7 introduces a new <code>try</code>-with-resources syntax, which automatically closes all the opened resources after <code>try</code> or <code>catch</code>, as follows. This produces much neater codes.</p>

<div><div id="highlighter_79200" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">try</code> <code class="java plain">(FileInputStream in = </code><code class="java keyword">new</code> <code class="java plain">FileInputStream(...)) {</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">......</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">......</code></div><div class="line number4 index3 alt1"><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number6 index5 alt1"><code class="java plain">}&nbsp; </code><code class="java comments">//# Automatically closes all opened resource in try (...).</code></div></div></td></tr></tbody></table></div></div>

<h4>Flushing the <span class="font-code">OutputStream</span></h4>
<p>In addition, the <code>OutputStream</code> provides a <code>flush()</code> method to flush the remaining bytes from the output buffer.</p>
<div><div id="highlighter_492134" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">flush() </code><code class="java keyword">throws</code> <code class="java plain">IOException&nbsp; </code><code class="java comments">//# Flush the output</code></div></div></td></tr></tbody></table></div></div>

<h4>Implementations of <span class="font-code">abstract <span class="font-code">InputStream/OutputStream</span></span></h4>

<p><code>InputStream</code> and <code>OutputStream</code> are <code>abstract</code>
 classes that cannot be instantiated. You need to choose an appropriate 
concrete subclass to establish a connection to a physical device. For 
example, you can instantiate a  <code>FileInputStream</code> or <code>FileOutputStream</code>   to establish a stream to a physical disk file.</p>

<h4>Layered (or Chained) I/O Streams</h4>

<p>The I/O streams are often layered or chained with other I/O streams, 
for purposes such as buffering, filtering, or data-format conversion 
(between raw bytes and primitive types). For example, we can layer a <code>BufferedInputStream</code> to a <code>FileInputStream</code> for buffered input, and stack a <code>DataInputStream</code> in front for formatted data input (using primitives such as <code>int</code>, <code>double</code>), as illustrated in the following diagrams.</p>

<img class="image-center" src="AppKubos_files/IO_LayeredInput.png">

<h4>File I/O Byte-Streams - <span class="font-code">FileInputStream &amp; <span class="font-code">FileOutputStream</span></span></h4>
<p><code>FileInputStream</code> and <code>FileOutputStream</code> are concrete implementations to the <code>abstract</code> classes <code>InputStream</code> and <code>OutputStream</code>, to support I/O from disk files.</p>

<h4>Buffered I/O Byte-Streams - <span class="font-code">BufferedInputStream &amp; <span class="font-code">BufferedOutputStream</span></span></h4>
<p>The <code>read()</code>/<code>write()</code> method in <code>InputStream</code>/<code>OutputStream</code>
 are designed to read/write a single byte of data on each call. This is 
grossly inefficient, as each call is handled by the underlying operating
 system (which may trigger a disk access, or other expensive 
operations). Buffering, which reads/writes a block of bytes from the 
external device into/from a memory buffer in a single I/O operation, is 
commonly applied to speed up the I/O.</p>
<p> <code>FileInputStream</code>/<code>FileOutputStream</code> is not buffered. It is often chained to a <code>BufferedInputStream</code> or <code>BufferedOutputStream</code>,
 which provides the buffering. To chain the streams together, simply 
pass an instance of one stream into the constructor of another stream. 
For example, the following codes chain a <code>FileInputStream</code> to a <code>BufferedInputStream</code>, and finally, a <code>DataInputStream</code>:</p>
<div><div id="highlighter_692614" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">FileInputStream fileIn = </code><code class="java keyword">new</code> <code class="java plain">FileInputStream(</code><code class="java string">"in.dat"</code><code class="java plain">);</code></div><div class="line number2 index1 alt1"><code class="java plain">BufferedInputStream bufferIn = </code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(fileIn);</code></div><div class="line number3 index2 alt2"><code class="java plain">DataInputStream dataIn = </code><code class="java keyword">new</code> <code class="java plain">DataInputStream(bufferIn);</code></div><div class="line number4 index3 alt1"><code class="java comments">//# or</code></div><div class="line number5 index4 alt2"><code class="java plain">DataInputStream in = </code><code class="java keyword">new</code> <code class="java plain">DataInputStream(</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(</code><code class="java string">"in.dat"</code><code class="java plain">)));</code></div></div></td></tr></tbody></table></div></div>


<p><span class="line-heading">Example 1: Copying a file byte-by-byte without Buffering.</span></p>

<div><div id="highlighter_86648" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">FileCopyNoBuffer {&nbsp; </code><code class="java comments">//# Pre-JDK 7</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String inFileStr = </code><code class="java string">"test-in.jpg"</code><code class="java plain">;</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String outFileStr = </code><code class="java string">"test-out.jpg"</code><code class="java plain">;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">FileInputStream in = </code><code class="java keyword">null</code><code class="java plain">;</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">FileOutputStream out = </code><code class="java keyword">null</code><code class="java plain">;</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">long</code> <code class="java plain">startTime, elapsedTime;&nbsp; </code><code class="java comments">//# for speed benchmarking</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print file length</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">File fileIn = </code><code class="java keyword">new</code> <code class="java plain">File(inFileStr);</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"File size is "</code> <code class="java plain">+ fileIn.length() + </code><code class="java string">" bytes"</code><code class="java plain">);</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">in = </code><code class="java keyword">new</code> <code class="java plain">FileInputStream(inFileStr);</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out = </code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(outFileStr);</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">startTime = System.nanoTime();</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">byteRead;</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read a raw byte, returns an int of 0 to 255.</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((byteRead = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write the least-significant byte of int, drop the upper 3 bytes</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(byteRead);</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">elapsedTime = System.nanoTime() - startTime;</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"Elapsed Time is "</code> <code class="java plain">+ (elapsedTime / </code><code class="java value">1000000.0</code><code class="java plain">) + </code><code class="java string">" msec"</code><code class="java plain">);</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">finally</code> <code class="java plain">{&nbsp; </code><code class="java comments">//# always close the I/O streams</code></div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(in != </code><code class="java keyword">null</code><code class="java plain">) in.close();</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(out != </code><code class="java keyword">null</code><code class="java plain">) out.close();</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number38 index37 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">File size is 417455 bytes
Elapsed Time is 3781.500581 msec</pre>

<p>This example copies a file by reading a byte from the input file and writing it to the output file. It uses <code>FileInputStream</code> and <code>FileOutputStream</code> directly without buffering. Notice that most the I/O methods "throws" <code>IOException</code>, which must be caught or declared to be thrown.

The method <code>close()</code> is programmed inside the <code>finally</code> clause. It is guaranteed to be run after <code>try</code> or <code>catch</code>. However, method <code>close()</code> also throws an <code>IOException</code>, and therefore must be enclosed inside a nested <code>try-catch</code> block, which makes the codes a little ugly.</p>

<p>I used <code>System.nanoTime()</code>, which was introduced in JDK 1.5, for a more accurate measure of the elapsed time, instead of the legacy  not-so-precise <code>System.currentTimeMillis()</code>. The output shows that it took about 4 seconds to copy a 400KB file.</p>
<p>As mentioned, JDK 1.7 introduces a new <code>try</code>-with-resources syntax, which automatically closes all the resources opened, after <code>try</code> or <code>catch</code>. For example, the above example can be re-written in a much neater manner as follow:</p>

<div><div id="highlighter_890413" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">FileCopyNoBufferJDK7 {</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String inFileStr = </code><code class="java string">"test-in.jpg"</code><code class="java plain">;</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String outFileStr = </code><code class="java string">"test-out.jpg"</code><code class="java plain">;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">long</code> <code class="java plain">startTime, elapsedTime;&nbsp; </code><code class="java comments">//# for speed benchmarking</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Check file length</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">File fileIn = </code><code class="java keyword">new</code> <code class="java plain">File(inFileStr);</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"File size is "</code> <code class="java plain">+ fileIn.length() + </code><code class="java string">" bytes"</code><code class="java plain">);</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# "try-with-resources" automatically closes all opened resources.</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(FileInputStream&nbsp; in&nbsp; = </code><code class="java keyword">new</code> <code class="java plain">FileInputStream(inFileStr);</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">FileOutputStream out = </code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(outFileStr)) {</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">startTime = System.nanoTime();</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">byteRead;</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read a raw byte, returns an int of 0 to 255.</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((byteRead = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write the least-significant byte of int, drop the upper 3 bytes</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(byteRead);</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">elapsedTime = System.nanoTime() - startTime;</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"Elapsed Time is "</code> <code class="java plain">+ (elapsedTime / </code><code class="java value">1000000.0</code><code class="java plain">) + </code><code class="java string">" msec"</code><code class="java plain">);</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number29 index28 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<p><span class="line-heading">Example 2: Copying a file with a Programmer-Managed Buffer.</span></p>

<div><div id="highlighter_795078" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">FileCopyUserBuffer {&nbsp; </code><code class="java comments">//# Pre-JDK 7</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String inFileStr = </code><code class="java string">"test-in.jpg"</code><code class="java plain">;</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String outFileStr = </code><code class="java string">"test-out.jpg"</code><code class="java plain">;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">FileInputStream in = </code><code class="java keyword">null</code><code class="java plain">;</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">FileOutputStream out = </code><code class="java keyword">null</code><code class="java plain">;</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">long</code> <code class="java plain">startTime, elapsedTime;&nbsp; </code><code class="java comments">//# for speed benchmarking</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Check file length</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">File fileIn = </code><code class="java keyword">new</code> <code class="java plain">File(inFileStr);</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"File size is "</code> <code class="java plain">+ fileIn.length() + </code><code class="java string">" bytes"</code><code class="java plain">);</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">in = </code><code class="java keyword">new</code> <code class="java plain">FileInputStream(inFileStr);</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out = </code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(outFileStr);</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">startTime = System.nanoTime();</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">byte</code><code class="java plain">[] byteBuf = </code><code class="java keyword">new</code> <code class="java keyword">byte</code><code class="java plain">[</code><code class="java value">4096</code><code class="java plain">];&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# 4K byte-buffer</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">numBytesRead;</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((numBytesRead = in.read(byteBuf)) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(byteBuf, </code><code class="java value">0</code><code class="java plain">, numBytesRead);</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">elapsedTime = System.nanoTime() - startTime;</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"Elapsed Time is "</code> <code class="java plain">+ (elapsedTime / </code><code class="java value">1000000.0</code><code class="java plain">) + </code><code class="java string">" msec"</code><code class="java plain">);</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">finally</code> <code class="java plain">{&nbsp; </code><code class="java comments">//# always close the streams</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(in != </code><code class="java keyword">null</code><code class="java plain">) in.close();</code></div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(out != </code><code class="java keyword">null</code><code class="java plain">) out.close();</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) { ex.printStackTrace(); }</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number34 index33 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">File size is 417455 bytes
Elapsed Time is 2.938921 msec</pre>

<p>This example again uses <code>FileInputStream</code> and <code>FileOutputStream</code>
 directly. However, instead of reading/writing one byte at a time, it 
reads/writes a 4KB block. This program took only 3 millisecond - a more 
than 1000 times speed-up compared with the previous example.</p>

<p>Larger buffer size, up to a certain limit, generally improves the I/O
 performance. However, there is a trade-off between speed-up the the 
memory usage. For file copying, a large buffer is certainly recommended.
 But for reading just a few bytes from a file, large buffer simply 
wastes the memory.</p>

<p>I re-write the program using JDK 1.7, and try on various buffer size on a much bigger file of 26MB.</p>

<div><div id="highlighter_736420" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">FileCopyUserBufferLoopJDK7 {</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String inFileStr = </code><code class="java string">"test-in.jpg"</code><code class="java plain">;</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String outFileStr = </code><code class="java string">"test-out.jpg"</code><code class="java plain">;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">long</code> <code class="java plain">startTime, elapsedTime;&nbsp; </code><code class="java comments">//# for speed benchmarking</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Check file length</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">File fileIn = </code><code class="java keyword">new</code> <code class="java plain">File(inFileStr);</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"File size is "</code> <code class="java plain">+ fileIn.length() + </code><code class="java string">" bytes"</code><code class="java plain">);</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code><code class="java plain">[] bufSizeKB = {</code><code class="java value">1</code><code class="java plain">, </code><code class="java value">2</code><code class="java plain">, </code><code class="java value">4</code><code class="java plain">, </code><code class="java value">8</code><code class="java plain">, </code><code class="java value">16</code><code class="java plain">, </code><code class="java value">32</code><code class="java plain">, </code><code class="java value">64</code><code class="java plain">, </code><code class="java value">256</code><code class="java plain">, </code><code class="java value">1024</code><code class="java plain">};&nbsp; </code><code class="java comments">//# in KB</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">bufSize;&nbsp; </code><code class="java comments">//# in bytes</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">run = </code><code class="java value">0</code><code class="java plain">; run &lt; bufSizeKB.length; run++) {</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">bufSize = bufSizeKB[run] * </code><code class="java value">1024</code><code class="java plain">;</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(FileInputStream in = </code><code class="java keyword">new</code> <code class="java plain">FileInputStream(inFileStr);</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">FileOutputStream out = </code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(outFileStr)) {</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">startTime = System.nanoTime();</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">byte</code><code class="java plain">[] byteBuf = </code><code class="java keyword">new</code> <code class="java keyword">byte</code><code class="java plain">[bufSize];</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">numBytesRead;</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((numBytesRead = in.read(byteBuf)) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(byteBuf, </code><code class="java value">0</code><code class="java plain">, numBytesRead);</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">elapsedTime = System.nanoTime() - startTime;</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%4dKB: %6.2fmsec%n"</code><code class="java plain">, bufSizeKB[run], (elapsedTime / </code><code class="java value">1000000.0</code><code class="java plain">));</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//#System.out.println("Elapsed Time is " + (elapsedTime / 1000000.0) + " msec");</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number33 index32 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">File size is 26246026 bytes <span class="color-comment">[26 MB]
   1KB: 573.54msec
   2KB: 316.43msec
   4KB: 178.47msec
   8KB: 116.32msec
  16KB:  85.61msec
  32KB:  65.92msec
  64KB:  57.81msec
 256KB:  63.38msec
1024KB:  98.87msec</span></pre>

<p>Increasing buffer size  helps only up to a certain point?!</p>

<p><span class="line-heading">Example 3: Copying a file with Buffered Streams.</span></p>

<div><div id="highlighter_158665" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">FileCopyBufferedStream {&nbsp; </code><code class="java comments">//# Pre-JDK 7</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String inFileStr = </code><code class="java string">"test-in.jpg"</code><code class="java plain">;</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String outFileStr = </code><code class="java string">"test-out.jpg"</code><code class="java plain">;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">BufferedInputStream in = </code><code class="java keyword">null</code><code class="java plain">;</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">BufferedOutputStream out = </code><code class="java keyword">null</code><code class="java plain">;</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">long</code> <code class="java plain">startTime, elapsedTime;&nbsp; </code><code class="java comments">//# for speed benchmarking</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Check file length</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">File fileIn = </code><code class="java keyword">new</code> <code class="java plain">File(inFileStr);</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"File size is "</code> <code class="java plain">+ fileIn.length() + </code><code class="java string">" bytes"</code><code class="java plain">);</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">in&nbsp; = </code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(inFileStr));</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out = </code><code class="java keyword">new</code> <code class="java plain">BufferedOutputStream(</code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(outFileStr));</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">startTime = System.nanoTime();</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">byteRead;</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((byteRead = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {&nbsp; </code><code class="java comments">//# Read byte-by-byte from buffer</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(byteRead);</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">elapsedTime = System.nanoTime() - startTime;</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"Elapsed Time is "</code> <code class="java plain">+ (elapsedTime / </code><code class="java value">1000000.0</code><code class="java plain">) + </code><code class="java string">" msec"</code><code class="java plain">);</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">finally</code> <code class="java plain">{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# always close the streams</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(in != </code><code class="java keyword">null</code><code class="java plain">) in.close();</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(out != </code><code class="java keyword">null</code><code class="java plain">) out.close();</code></div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) { ex.printStackTrace(); }</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number33 index32 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">File size is 417455 bytes
Elapsed Time is 61.834954 msec</pre>

<p>In this example, I chain the <code>FileInputStream</code> with <code>BufferedInputStream</code>,  <code>FileOutputStream</code> with <code>BufferedOutputStream</code>,
 and read/write byte-by-byte. The JRE decides on the buffer size. The 
program took 62 milliseconds, about 60 times speed-up compared with 
example 1, but slower than the programmer-managed buffer.</p>

<p>The JDK 1.7 version of the above example is as follows:</p>
<div><div id="highlighter_723944" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">FileCopyBufferedStreamJDK7 {</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String inFileStr = </code><code class="java string">"test-in.jpg"</code><code class="java plain">;</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String outFileStr = </code><code class="java string">"test-out.jpg"</code><code class="java plain">;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">long</code> <code class="java plain">startTime, elapsedTime;&nbsp; </code><code class="java comments">//# for speed benchmarking</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Check file length</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">File fileIn = </code><code class="java keyword">new</code> <code class="java plain">File(inFileStr);</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"File size is "</code> <code class="java plain">+ fileIn.length() + </code><code class="java string">" bytes"</code><code class="java plain">);</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedInputStream in = </code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(inFileStr));</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">BufferedOutputStream out = </code><code class="java keyword">new</code> <code class="java plain">BufferedOutputStream(</code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(outFileStr))) {</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">startTime = System.nanoTime();</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">byteRead;</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((byteRead = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(byteRead);</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">elapsedTime = System.nanoTime() - startTime;</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"Elapsed Time is "</code> <code class="java plain">+ (elapsedTime / </code><code class="java value">1000000.0</code><code class="java plain">) + </code><code class="java string">" msec"</code><code class="java plain">);</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number25 index24 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>


<h4>Formatted Data-Streams: <span class="font-code">DataInputStream &amp; <span class="font-code">DataOutputStream</span></span></h4>

<p>The <code>DataInputStream</code> and <code>DataOutputStream</code> can be stacked on top of any <code>InputStream</code> and <code>OutputStream</code> to parse the raw bytes so as to perform I/O operations in the desired data format, such as <code>int</code> and <code>double</code>.</p>

<p>To use <code>DataInputStream</code> for formatted input, you can chain up the input streams <code></code> as follows:</p>
<div><div id="highlighter_382437" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">DataInputStream in = </code><code class="java keyword">new</code> <code class="java plain">DataInputStream(</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(</code><code class="java string">"in.dat"</code><code class="java plain">)));</code></div></div></td></tr></tbody></table></div></div>

<p><code>DataInputStream</code> implements <code>DataInput</code> interface, which provides methods to read formatted primitive data and <code>String</code>, such as:</p>
<div><div id="highlighter_930978" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# 8 Primitives</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">int</code> <code class="java plain">readInt() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Read 4 bytes and convert into int</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">double</code> <code class="java plain">readDoube() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;&nbsp; </code><code class="java comments">//# Read 8 bytes and convert into double </code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">byte</code> <code class="java plain">readByte() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">char</code> <code class="java plain">readChar() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">short</code> <code class="java plain">readShort() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number7 index6 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">long</code> <code class="java plain">readLong() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number8 index7 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">boolean</code> <code class="java plain">readBoolean() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Read 1 byte. Convert to false if zero</code></div><div class="line number9 index8 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">float</code> <code class="java plain">readFloat() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number11 index10 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">int</code> <code class="java plain">readUnsignedByte() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;&nbsp;&nbsp; </code><code class="java comments">//# Read 1 byte in [0, 255] upcast to int</code></div><div class="line number12 index11 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">int</code> <code class="java plain">readUnsignedShort() </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;&nbsp; </code><code class="java comments">//# Read 2 bytes in [0, 65535], same as char, upcast to int</code></div><div class="line number13 index12 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">readFully(</code><code class="java keyword">byte</code><code class="java plain">[] b, </code><code class="java keyword">int</code> <code class="java plain">off, </code><code class="java keyword">int</code> <code class="java plain">len) </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number14 index13 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">readFully(</code><code class="java keyword">byte</code><code class="java plain">[] b) </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number16 index15 alt1"><code class="java comments">//# Strings</code></div><div class="line number17 index16 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java plain">String readLine() </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read a line (until newline), convert each byte into a char - no unicode support.</code></div><div class="line number19 index18 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java plain">String readUTF() </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# read a UTF-encoded string with firt two bytes indicating its UTF bytes length</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number22 index21 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">int</code> <code class="java plain">skipBytes(</code><code class="java keyword">int</code> <code class="java plain">n)&nbsp; </code><code class="java comments">//# Skip a number of bytes</code></div></div></td></tr></tbody></table></div></div>

<p>Similarly, you can stack the <code>DataOutputStream</code> as follows:</p>
<div><div id="highlighter_5584" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">DataOutputStream out = </code><code class="java keyword">new</code> <code class="java plain">DataOutputStream(</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedOutputStream(</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(</code><code class="java string">"out.dat"</code><code class="java plain">)));</code></div></div></td></tr></tbody></table></div></div>

<p><code>DataOutputStream</code> implements <code>DataOutput</code> interface, which provides methods to write formatted primitive data and <code>String</code>. For examples,</p>
<div><div id="highlighter_117666" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# 8 primitive types</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeInt(</code><code class="java keyword">int</code> <code class="java plain">i) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Write the int as 4 bytes</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeFloat(</code><code class="java keyword">float</code> <code class="java plain">f) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeDoube(</code><code class="java keyword">double</code> <code class="java plain">d) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion; </code><code class="java comments">//# Write the double as 8 bytes</code></div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeByte(</code><code class="java keyword">int</code> <code class="java plain">b) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# least-significant byte</code></div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeShort(</code><code class="java keyword">int</code> <code class="java plain">s) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# two lower bytes</code></div><div class="line number7 index6 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeLong(</code><code class="java keyword">long</code> <code class="java plain">l) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number8 index7 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeBoolean(</code><code class="java keyword">boolean</code> <code class="java plain">b) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number9 index8 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeChar(</code><code class="java keyword">int</code> <code class="java plain">i) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number11 index10 alt2"><code class="java comments">//# String</code></div><div class="line number12 index11 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeBytes(String str) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;&nbsp; </code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# least-significant byte of each char</code></div><div class="line number14 index13 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeChars(String str) </code><code class="java keyword">throws</code> <code class="java plain">IOExcpetion;</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write String as UCS-2 16-bit char, Big-endian (big byte first)</code></div><div class="line number16 index15 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeUTF(String str) </code><code class="java keyword">throws</code> <code class="java plain">IOException;&nbsp;&nbsp; </code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write String as UTF, with first two bytes indicating UTF bytes length</code></div><div class="line number18 index17 alt1">&nbsp;</div><div class="line number19 index18 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">write(</code><code class="java keyword">byte</code><code class="java plain">[] b, </code><code class="java keyword">int</code> <code class="java plain">off, </code><code class="java keyword">int</code> <code class="java plain">len) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number20 index19 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">write(</code><code class="java keyword">byte</code><code class="java plain">[] b) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number21 index20 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">write(</code><code class="java keyword">int</code> <code class="java plain">b) </code><code class="java keyword">throws</code> <code class="java plain">IOException&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Write the least-significant byte</code></div></div></td></tr></tbody></table></div></div>

<p>Example: The following program writes some primitives to a disk file.
 It then reads the raw bytes to check how the primitives were stored. 
Finally, it reads the data as primitives.</p>

<div><div id="highlighter_26208" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div><div class="line number39 index38 alt2">39</div><div class="line number40 index39 alt1">40</div><div class="line number41 index40 alt2">41</div><div class="line number42 index41 alt1">42</div><div class="line number43 index42 alt2">43</div><div class="line number44 index43 alt1">44</div><div class="line number45 index44 alt2">45</div><div class="line number46 index45 alt1">46</div><div class="line number47 index46 alt2">47</div><div class="line number48 index47 alt1">48</div><div class="line number49 index48 alt2">49</div><div class="line number50 index49 alt1">50</div><div class="line number51 index50 alt2">51</div><div class="line number52 index51 alt1">52</div><div class="line number53 index52 alt2">53</div><div class="line number54 index53 alt1">54</div><div class="line number55 index54 alt2">55</div><div class="line number56 index55 alt1">56</div><div class="line number57 index56 alt2">57</div><div class="line number58 index57 alt1">58</div><div class="line number59 index58 alt2">59</div><div class="line number60 index59 alt1">60</div><div class="line number61 index60 alt2">61</div><div class="line number62 index61 alt1">62</div><div class="line number63 index62 alt2">63</div><div class="line number64 index63 alt1">64</div><div class="line number65 index64 alt2">65</div><div class="line number66 index65 alt1">66</div><div class="line number67 index66 alt2">67</div><div class="line number68 index67 alt1">68</div><div class="line number69 index68 alt2">69</div><div class="line number70 index69 alt1">70</div><div class="line number71 index70 alt2">71</div><div class="line number72 index71 alt1">72</div><div class="line number73 index72 alt2">73</div><div class="line number74 index73 alt1">74</div><div class="line number75 index74 alt2">75</div><div class="line number76 index75 alt1">76</div><div class="line number77 index76 alt2">77</div><div class="line number78 index77 alt1">78</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">TestDataIOStream {</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String filename = </code><code class="java string">"data-out.dat"</code><code class="java plain">;</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String message = </code><code class="java string">"Hi,您好!"</code><code class="java plain">;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write primitives to an output file</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(DataOutputStream out =</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">DataOutputStream(</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedOutputStream(</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(filename)))) {</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeByte(</code><code class="java value">127</code><code class="java plain">);</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeShort(</code><code class="java value">0xFFFF</code><code class="java plain">);&nbsp; </code><code class="java comments">//# -1</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeInt(</code><code class="java value">0xABCD</code><code class="java plain">);</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeLong(0x1234_5678);&nbsp; </code><code class="java comments">//# JDK 7 syntax</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeFloat(</code><code class="java value">11</code><code class="java plain">.22f);</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeDouble(</code><code class="java value">55.66</code><code class="java plain">);</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeBoolean(</code><code class="java keyword">true</code><code class="java plain">);</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeBoolean(</code><code class="java keyword">false</code><code class="java plain">);</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; message.length(); i++) {</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeChar(message.charAt(i));</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeChars(message);</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeBytes(message);</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.flush();</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read raw bytes and print in Hex</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedInputStream in =</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(filename))) {</code></div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">inByte;</code></div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((inByte = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, inByte);&nbsp;&nbsp; </code><code class="java comments">//# Print Hex codes</code></div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number38 index37 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%n%n"</code><code class="java plain">);</code></div><div class="line number39 index38 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number40 index39 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number41 index40 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number42 index41 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number43 index42 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read primitives</code></div><div class="line number44 index43 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(DataInputStream in =</code></div><div class="line number45 index44 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">DataInputStream(</code></div><div class="line number46 index45 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code></div><div class="line number47 index46 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(filename)))) {</code></div><div class="line number48 index47 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"byte:&nbsp;&nbsp;&nbsp; "</code> <code class="java plain">+ in.readByte());</code></div><div class="line number49 index48 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"short:&nbsp;&nbsp; "</code> <code class="java plain">+ in.readShort());</code></div><div class="line number50 index49 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"int:&nbsp;&nbsp;&nbsp;&nbsp; "</code> <code class="java plain">+ in.readInt());</code></div><div class="line number51 index50 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"long:&nbsp;&nbsp;&nbsp; "</code> <code class="java plain">+ in.readLong());</code></div><div class="line number52 index51 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"float:&nbsp;&nbsp; "</code> <code class="java plain">+ in.readFloat());</code></div><div class="line number53 index52 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"double:&nbsp; "</code> <code class="java plain">+ in.readDouble());</code></div><div class="line number54 index53 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"boolean: "</code> <code class="java plain">+ in.readBoolean());</code></div><div class="line number55 index54 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"boolean: "</code> <code class="java plain">+ in.readBoolean());</code></div><div class="line number56 index55 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number57 index56 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"char:&nbsp;&nbsp;&nbsp; "</code><code class="java plain">);</code></div><div class="line number58 index57 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; message.length(); i++) {</code></div><div class="line number59 index58 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(in.readChar());</code></div><div class="line number60 index59 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number61 index60 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number62 index61 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number63 index62 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"chars:&nbsp;&nbsp; "</code><code class="java plain">);</code></div><div class="line number64 index63 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; message.length(); i++) {</code></div><div class="line number65 index64 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(in.readChar());</code></div><div class="line number66 index65 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number67 index66 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number68 index67 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number69 index68 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"bytes:&nbsp;&nbsp; "</code><code class="java plain">);</code></div><div class="line number70 index69 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; message.length(); i++) {</code></div><div class="line number71 index70 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print((</code><code class="java keyword">char</code><code class="java plain">)in.readByte());</code></div><div class="line number72 index71 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number73 index72 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number74 index73 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number75 index74 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number76 index75 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number77 index76 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number78 index77 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output"><span class="underline">7F   <span class="underline">FF FF <span class="underline">00 00 AB CD <span class="underline">00 00 00 00 00 0F 42 3F
<span class="color-comment">byte short int         long
<span class="underline">41 33 85 1F <span class="underline">40 4B D4 7A E1 47 AE 14
<span class="color-comment">float       double
<span class="underline">01      <span class="underline">00
<span class="color-comment">boolean boolean
<span class="underline">00 48 00 69 00 2C 60 A8 59 7D 00 21
<span class="color-comment">H     i     ,     您    好    !
<span class="underline">00 48 00 69 00 2C 60 A8 59 7D 00 21
<span class="color-comment">H     i     ,     您    好    !
48 69 2C A8 7D 21
<span class="color-comment">[low byte of the char only]
 
byte:    127
short:   -1
int:     43981
long:    305419896
float:   11.22
double:  55.66
boolean: true
boolean: false
char:    Hi,您好!
chars:   Hi,您好!
bytes:   Hi,?}!</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></pre>

<p>The data stored in the disk are exactly in the same form as in the 
Java program internally (e.g., UCS-2 for characters). The byte-order is 
big-endian (big byte first, or most significant byte in lowest address).</p>

<h4>Network I/O</h4>
<p>[In Java Networking]</p>

<h3>Character-Based I/O &amp; Character Streams</h3>

<img class="image-center" src="AppKubos_files/IO_InputOutputReadersWriters.png">

<p>Java internally stores characters (<code>char</code> type) in 16-bit 
UCS-2 character set. But the external data source/sink could store 
characters in other character set (e.g., US-ASCII, ISO-8859-x, UTF-8, 
UTF-16, and many others), in fixed length of 8-bit or 16-bit, or in 
variable length of 1 to 4 bytes. [Read "<a href="http://appkubos.com/java/DataRepresentation.html//#charencoding">Character Sets and Encoding Schemes</a>"].
 Hence, Java has to differentiate between byte-based I/O for processing 
8-bit raw bytes, and character-based I/O for processing texts. The 
character streams needs to translate between the character set used by 
external I/O devices and Java internal UCS-2 format. For example, the 
character '您' is stored as "<code>60 A8</code>" in UCS-2 (Java internal), "<code>E6 82 A8</code>" in UTF8, "<code>C4 FA</code>" in GBK/GB2312, and "<code>B1 7A</code>" in BIG5. If this character is to be written to a file uses UTF-8, the character stream needs to translate "<code>60 A8</code>" to "<code>E6 82 A8</code>". The reserve takes place in a reading operation.</p>

<p>The byte/character streams refer to the unit of operation within the 
Java programs, which does not necessary correspond to the amount of data
 transferred from/to the external I/O devices. This is because some 
charsets use fixed-length of 8-bit (e.g., US-ASCII, ISO-8859-1) or 
16-bit (e.g., UCS-16), while some use variable-length of 1-4 bytes 
(e.g., UTF-8, UTF-16, UTF-16-BE, UTF-16-LE, GBK, BIG5). When a character
 stream is used to read an 8-bit ASCII file, an 8-bit data is read from 
the file and put into the 16-bit <code>char</code> location of the Java program.</p>

<h4>Abstract superclass <span class="font-code">Reader and <span class="font-code">Writer</span></span></h4>
<p>Other than the unit of operation and charset conversion (which is 
extremely complex), character-based I/O is almost identical to 
byte-based I/O. Instead of <code>InputStream</code> and <code>OutputStream</code>, we use <code>Reader</code> and <code>Writer</code> for character-based I/O.</p>
<p>The <code>abstract</code> superclass <code>Reader</code> operates on <code>char</code>. It declares an <code>abstract</code> method <code>read()</code> to read one character from the input source. <code>read()</code> returns the character as an <code>int</code> between 0 to 65535 (a <code>char</code> in Java can be treated as an unsigned 16-bit integer); or -1 if end-of-stream is detected; or throws an <code>IOException</code> if I/O error occurs. There are also two variations of <code>read()</code> to read a block of characters into <code>char</code>-array.</p>
<div><div id="highlighter_817466" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">abstract</code> <code class="java keyword">int</code> <code class="java plain">read() </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">read(</code><code class="java keyword">char</code><code class="java plain">[] chars, </code><code class="java keyword">int</code> <code class="java plain">offset, </code><code class="java keyword">int</code> <code class="java plain">length) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">read(</code><code class="java keyword">char</code><code class="java plain">[] chars) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<p>The <code>abstract</code> superclass <code>Writer</code> declares an <code>abstract</code> method <code>write()</code>, which writes a character to the output sink. The lower 2 bytes of the <code>int</code> argument is written out; while the upper 2 bytes are discarded.</p>
<div><div id="highlighter_107442" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java keyword">abstract</code> <code class="java keyword">void</code> <code class="java plain">write(</code><code class="java keyword">int</code> <code class="java plain">aChar) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">write(</code><code class="java keyword">char</code><code class="java plain">[] chars, </code><code class="java keyword">int</code> <code class="java plain">offset, </code><code class="java keyword">int</code> <code class="java plain">length) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">write(</code><code class="java keyword">char</code><code class="java plain">[] chars) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<h4>File I/O Character-Streams - <span class="font-code">FileReader &amp; <span class="font-code">FileWriter</span></span></h4>

<p><code>FileReader</code> and <code>FileWriter</code> are concrete implementations to the <code>abstract</code> superclasses <code>Reader</code> and <code>Writer</code>, to support I/O from disk files. <code>FileReader</code>/<code>FileWriter</code>
 assumes  that the default character encoding (charset) is used for the 
disk file. The default charset is kept in the JVM's system property "<code>file.encoding</code>". You can get the default charset via <code>static</code> method <code>java.nio.charset.Charset.defaultCharset()</code> or <code>System.getProperty("file.encoding")</code>. It is probable safe to use <code>FileReader</code>/<code>FileWriter</code>
 for ASCII texts, provided that the default charset is compatible to 
ASCII (such as US-ASCII, ISO-8859-x, UTF-8, and many others, but NOT 
UTF-16, UTF-16BE, UTF-16LE and many others). Use of <code>FileReader/FileWriter</code> is NOT recommended as you have no control of the file encoding charset.</p>

<h4>Buffered I/O Character-Streams - <span class="font-code">BufferedReader &amp; <span class="font-code">BufferedWriter</span></span></h4>

<p><code>BufferedReader</code> and <code>BufferedWriter</code> can be stacked on top of <code>FileReader/FileWriter</code> or other character streams to perform buffered I/O, instead of character-by-character. <code>BufferedReader</code> provides a new method <code>readLine()</code>, which reads a line and returns a <code>String</code> (without the line delimiter). Lines could be delimited by "<code>\n</code>" (Unix), "<code>\r\n</code>" (Windows), or "<code>\r</code>" (Mac).</p>

<h5>Example</h5>
<div><div id="highlighter_864576" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java comments">//# Write a text message to an output file, then read it back.</code></div><div class="line number3 index2 alt2"><code class="java comments">// FileReader/FileWriter uses the default charset for file encoding.</code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">BufferedFileReaderWriterJDK7 {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String strFilename = </code><code class="java string">"out.txt"</code><code class="java plain">;</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String message = </code><code class="java string">"Hello, world!\nHello, world again!\n"</code><code class="java plain">;&nbsp; </code><code class="java comments">//# 2 lines of texts</code></div><div class="line number8 index7 alt1">&nbsp;</div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print the default charset</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(java.nio.charset.Charset.defaultCharset());</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedWriter out = </code><code class="java keyword">new</code> <code class="java plain">BufferedWriter(</code><code class="java keyword">new</code> <code class="java plain">FileWriter(strFilename))) {</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(message);</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.flush();</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedReader in = </code><code class="java keyword">new</code> <code class="java plain">BufferedReader(</code><code class="java keyword">new</code> <code class="java plain">FileReader(strFilename))) {</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String inLine;</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((inLine = in.readLine()) != </code><code class="java keyword">null</code><code class="java plain">) {&nbsp; </code><code class="java comments">//# exclude newline</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(inLine);</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number28 index27 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<h4>Character Set (or Charset) - Package <span class="font-code">java.nio.charset (JDK 1.4)</span></h4>

<p>JDK 1.4 provides a new package <code>java.nio.charset</code> as part 
of NIO (New IO) to support character translation between the Unicode 
(UCS-2) used internally in Java program  and external devices which 
could be encoded in any other format (e.g., US-ASCII, ISO-8859-x, UTF-8,
 UTF-16, UTF-16BE, UTF-16LE, and etc.)</p>

<p>The main class <code>java.nio.charset.Charset</code> provides <code>static</code>
 methods for testing whether a particular   charset is supported, 
locating charset instances by name, and listing all the available 
charsets and the default charset.</p>

<div><div id="highlighter_737661" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">SortedMap&lt;String,Charset&gt; availableCharsets()&nbsp; </code><code class="java comments">//# lists all the available charsets</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Charset defaultCharset()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Returns the default charset</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Charset forName(String charsetName)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Returns a Charset instance for the given charset name (in String)</code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">isSupported(String charsetName)&nbsp; </code><code class="java comments">//# Tests if this charset name is supported</code></div></div></td></tr></tbody></table></div></div>

<h5>Example</h5>
<div><div id="highlighter_674200" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.nio.charset.Charset;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">TestCharset {</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print the default Charset</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"The defalut charset is "</code> <code class="java plain">+ Charset.defaultCharset());</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"The defalut charset is "</code> <code class="java plain">+ System.getProperty(</code><code class="java string">"file.encoding"</code><code class="java plain">));</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print the list of available Charsets in name=Charset</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"The available charsets are:"</code><code class="java plain">);</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(Charset.availableCharsets());</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Check if the given charset name is supported</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(Charset.isSupported(</code><code class="java string">"UTF-8"</code><code class="java plain">));&nbsp; </code><code class="java comments">//# true</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(Charset.isSupported(</code><code class="java string">"UTF8"</code><code class="java plain">));&nbsp;&nbsp; </code><code class="java comments">//# true</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(Charset.isSupported(</code><code class="java string">"UTF_8"</code><code class="java plain">));&nbsp; </code><code class="java comments">//# false</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Get an instance of a Charset</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Charset charset = Charset.forName(</code><code class="java string">"UTF8"</code><code class="java plain">);</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print this Charset name</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(charset.name());&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# "UTF-8"</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print all the other aliases</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(charset.aliases());&nbsp; </code><code class="java comments">//# [UTF8, unicolor-1-1-utf-8]</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number24 index23 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<p>The default charset for file encoding is kept in the system property "<code>file.encoding</code>". To change the JVM's default charset for file encoding, you can use command-line VM option "<code>-Dfile.encoding</code>". For example, the following command run the program with default charset of UTF-8.</p>

<pre class="color-command">&gt; java -Dfile.encoding=UTF-8 TestCharset</pre>

<p>Most importantly, the <code>Charset</code> class provides methods to 
encode/decode characters from UCS-2 used in Java program and the 
specific charset used in the external devices (such as UTF-8).</p>

<div><div id="highlighter_581469" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java plain">ByteBuffer encode(String s)</code></div><div class="line number2 index1 alt1"><code class="java plain">&lt;span </code><code class="java keyword">class</code><code class="java plain">=</code><code class="java string">"color-comment"</code><code class="java plain">&gt;</code><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java plain">ByteBuffer encode(CharBuffer cb)</code></div><div class="line number3 index2 alt2"><code class="java comments">//# Encodes Unicode UCS-2 characters in the CharBuffer/String </code></div><div class="line number4 index3 alt1"><code class="java comments">//&nbsp; into a "byte sequence" using this charset, and returns a ByteBuffer.</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java plain">CharBuffer decode(ByteBuffer bb)</code></div><div class="line number7 index6 alt2"><code class="java comments">//# Decode the byte sequence encoded using this charset in the ByteBuffer </code></div><div class="line number8 index7 alt1"><code class="java comments">//&nbsp; to Unicode UCS-2, and return a charBuffer.&lt;/span&gt;</code></div></div></td></tr></tbody></table></div></div>

<p>The <code>encode()</code>/<code>decode()</code> methods operate on <code>ByteBuffer</code> and <code>CharBuffer</code> introduced also in JDK 1.4, which will be explain in the New I/O section.</p>

<p><span class="line-heading">Example: The following example encodes 
some Unicode texts in various encoding scheme, and display the Hex codes
 of the encoded byte sequences.</span></p>

<div><div id="highlighter_536215" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.nio.ByteBuffer;</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.nio.CharBuffer;</code></div><div class="line number3 index2 alt2"><code class="java keyword">import</code> <code class="java plain">java.nio.charset.Charset;</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">TestCharsetEncodeDecode {</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Try these charsets for encoding</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String[] charsetNames = {</code><code class="java string">"US-ASCII"</code><code class="java plain">, </code><code class="java string">"ISO-8859-1"</code><code class="java plain">, </code><code class="java string">"UTF-8"</code><code class="java plain">, </code><code class="java string">"UTF-16"</code><code class="java plain">,</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java string">"UTF-16BE"</code><code class="java plain">, </code><code class="java string">"UTF-16LE"</code><code class="java plain">, </code><code class="java string">"GBK"</code><code class="java plain">, </code><code class="java string">"BIG5"</code><code class="java plain">};</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String message = </code><code class="java string">"Hi,您好!"</code><code class="java plain">;&nbsp; </code><code class="java comments">//# Unicode message to be encoded</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print UCS-2 in hex codes</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%10s: "</code><code class="java plain">, </code><code class="java string">"UCS-2"</code><code class="java plain">);</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; message.length(); i++) {</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%04X "</code><code class="java plain">, (</code><code class="java keyword">int</code><code class="java plain">)message.charAt(i));</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(String charsetName: charsetNames) {</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Get a Charset instance given the charset name string</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Charset charset = Charset.forName(charsetName);</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%10s: "</code><code class="java plain">, charset.name());</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Encode the Unicode UCS-2 characters into a byte sequence in this charset.</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ByteBuffer bb = charset.encode(message);</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">(bb.hasRemaining()) {</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, bb.get());&nbsp; </code><code class="java comments">//# Print hex code</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">bb.rewind();</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number33 index32 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">     UCS-2: 0048 0069 002C 60A8 597D 0021 <span class="color-comment">[16-bit fixed-length]
            <span class="color-comment">H    i    ,    您   好   !
  US-ASCII: 48 69 2C 3F 3F 21 <span class="color-comment">[8-bit fixed-length]
            <span class="color-comment">H  i  ,  ?  ?  !
ISO-8859-1: 48 69 2C 3F 3F 21 <span class="color-comment">[8-bit fixed-length]
            <span class="color-comment">H  i  ,  ?  ?  !
     UTF-8: 48 69 2C <span class="underline">E6 82 A8 <span class="underline">E5 A5 BD 21 <span class="color-comment">[1-4 bytes variable-length]
            <span class="color-comment">H  i  ,  您       好       !
    UTF-16: <span class="underline">FE FF <span class="underline">00 48 <span class="underline">00 69 <span class="underline">00 2C <span class="underline">60 A8 <span class="underline">59 7D <span class="underline">00 21 <span class="color-comment">[2-4 bytes variable-length]
            <span class="color-comment">BOM   H     i     ,     您    好    !     [Byte-Order-Mark indicates Big-Endian]
  UTF-16BE: <span class="underline">00 48 <span class="underline">00 69 <span class="underline">00 2C <span class="underline">60 A8 <span class="underline">59 7D <span class="underline">00 21 <span class="color-comment">[2-4 bytes variable-length]
            <span class="color-comment">H     i     ,     您    好    !
  UTF-16LE: <span class="underline">48 00 <span class="underline">69 00 <span class="underline">2C 00 <span class="underline">A8 60 <span class="underline">7D 59 <span class="underline">21 00 <span class="color-comment">[2-4 bytes variable-length]
            <span class="color-comment">H     i     ,     您    好    !
       GBK: 48 69 2C <span class="underline">C4 FA <span class="underline">BA C3 21 <span class="color-comment">[1-2 bytes variable-length]
            <span class="color-comment">H  i  ,  您    好    !
      Big5: 48 69 2C <span class="underline">B1 7A <span class="underline">A6 6E 21 <span class="color-comment">[1-2 bytes variable-length]
            <span class="color-comment">H  i  ,  您    好    !
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></pre>

<p><span class="line-heading">Example: The following example tries out the encoding/decoding on <code>CharBuffer</code> and <code>ByteBuffer</code>. Buffers will be discussed later under New I/O.</span></p>

<div><div id="highlighter_866302" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div><div class="line number39 index38 alt2">39</div><div class="line number40 index39 alt1">40</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.nio.ByteBuffer;</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.nio.CharBuffer;</code></div><div class="line number3 index2 alt2"><code class="java keyword">import</code> <code class="java plain">java.nio.charset.Charset;</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">TestCharsetEncodeByteBuffer {</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">byte</code><code class="java plain">[] bytes = {</code><code class="java value">0x00</code><code class="java plain">, </code><code class="java value">0x48</code><code class="java plain">, </code><code class="java value">0x00</code><code class="java plain">, </code><code class="java value">0x69</code><code class="java plain">, </code><code class="java value">0x00</code><code class="java plain">, </code><code class="java value">0x2C</code><code class="java plain">,</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java value">0x60</code><code class="java plain">, (</code><code class="java keyword">byte</code><code class="java plain">)</code><code class="java value">0xA8</code><code class="java plain">, </code><code class="java value">0x59</code><code class="java plain">, </code><code class="java value">0x7D</code><code class="java plain">, </code><code class="java value">0x00</code><code class="java plain">, </code><code class="java value">0x21</code><code class="java plain">};&nbsp; </code><code class="java comments">//# "Hi,您好!"</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print UCS-2 in hex codes</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%10s: "</code><code class="java plain">, </code><code class="java string">"UCS-2"</code><code class="java plain">);</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; bytes.length; i++) {</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, bytes[i]);</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Charset charset = Charset.forName(</code><code class="java string">"UTF-8"</code><code class="java plain">);</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Encode from UCS-2 to UTF-8</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Create a ByteBuffer by wrapping a byte array</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ByteBuffer bb = ByteBuffer.wrap(bytes);</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Create a CharBuffer from a view of this ByteBuffer</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">CharBuffer cb = bb.asCharBuffer();</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ByteBuffer bbOut = charset.encode(cb);</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print hex code</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%10s: "</code><code class="java plain">, charset.name());</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">(bbOut.hasRemaining()) {</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, bbOut.get());</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Decode from UTF-8 to UCS-2</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">bbOut.rewind();</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">CharBuffer cbOut = charset.decode(bbOut);</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%10s: "</code><code class="java plain">, </code><code class="java string">"UCS-2"</code><code class="java plain">);</code></div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">(cbOut.hasRemaining()) {</code></div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">char</code> <code class="java plain">aChar = cbOut.get();</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"'%c'[%04X] "</code><code class="java plain">, aChar, (</code><code class="java keyword">int</code><code class="java plain">)aChar);&nbsp; </code><code class="java comments">//# Print char &amp; hex code</code></div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number38 index37 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number39 index38 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number40 index39 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">UCS-2: 00 48 00 69 00 2C 60 A8 59 7D 00 21
UTF-8: 48 69 2C <span class="underline">E6 82 A8 <span class="underline">E5 A5 BD 21
UCS-2: 'H'[0048] 'i'[0069] ','[002C] '您'[60A8] '好'[597D] '!'[0021]</span></span></pre>

<h4>Text File I/O - <span class="font-code">InputStreamReader and <span class="font-code">OutputStreamWriter</span></span></h4>
<p>As mentioned, Java internally stores characters (<code>char</code> 
type) in 16-bit   UCS-2 character set. But the external data source/sink
 could store   characters in other character set (e.g., US-ASCII, 
ISO-8859-x, UTF-8,   UTF-16, and many others), in fixed length of 8-bit 
or 16-bit, or in   variable length of 1 to 4 bytes. The <code>FileReader</code>/<code>FileWriter</code> introduced earlier uses the default charset for decoding/encoding, resulted in non-portable programs.</p>
<p> To choose the charset, you need to use <code>InputStreamReader</code> and <code>OutputStreamWriter</code>. <code>InputStreamReader</code> and <code>OutputStreamWriter</code> are considered to be byte-to-character "bridge" streams.</p>
<p>You can choose the character set in the <code>InputStreamReader</code>'s constructor:</p>
<div><div id="highlighter_924139" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java plain">InputStreamReader(InputStream in)&nbsp;&nbsp; </code><code class="java comments">//# Use default charset</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">InputStreamReader(InputStream in, String charsetName) </code><code class="java keyword">throws</code> <code class="java plain">UnsupportedEncodingException</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java plain">InputStreamReader(InputStream in, Charset cs)</code></div></div></td></tr></tbody></table></div></div>

<p>You can list the available charsets via <code>static</code> method <code>java.nio.charset.Charset.availableCharsets()</code>. The commonly-used <code>Charset</code> names supported by Java are:</p>
<ul>
<li>"<code>US-ASCII</code>": 7-bit ASCII (aka ISO646-US)</li>
<li>"<code>ISO-8859-1</code>": Latin-1</li>
<li>"<code>UTF-8</code>": Most commonly-used encoding scheme for Unicode</li>
<li>"<code>UTF-16BE</code>": Big-endian (big byte first) (big-endian is usually the default)</li>
<li> "<code>UTF-16LE</code>": Little-endian (little byte first)</li>
<li>"<code>UTF-16</code>": with a 2-byte BOM (Byte-Order-Mark) to specify the byte order. FE FF indicates big-endian, FF FE indicates little-endian.</li>
</ul>
<p>As the <code>InputStreamReader</code>/<code>OutputStreamWriter</code> often needs to read/write in multiple bytes, it is best to wrap it with a <code>BufferedReader</code>/<code>BufferedWriter</code>.</p>

<p><span class="line-heading">Example: The following program writes 
Unicode texts to a disk file using various  charsets for file encoding. 
It then reads the file byte-by-byte (via a byte-based input stream) to 
check the encoded characters in the various charsets. Finally, it reads 
the file using the character-based reader.</span></p>

<div><div id="highlighter_393457" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div><div class="line number39 index38 alt2">39</div><div class="line number40 index39 alt1">40</div><div class="line number41 index40 alt2">41</div><div class="line number42 index41 alt1">42</div><div class="line number43 index42 alt2">43</div><div class="line number44 index43 alt1">44</div><div class="line number45 index44 alt2">45</div><div class="line number46 index45 alt1">46</div><div class="line number47 index46 alt2">47</div><div class="line number48 index47 alt1">48</div><div class="line number49 index48 alt2">49</div><div class="line number50 index49 alt1">50</div><div class="line number51 index50 alt2">51</div><div class="line number52 index51 alt1">52</div><div class="line number53 index52 alt2">53</div><div class="line number54 index53 alt1">54</div><div class="line number55 index54 alt2">55</div><div class="line number56 index55 alt1">56</div><div class="line number57 index56 alt2">57</div><div class="line number58 index57 alt1">58</div><div class="line number59 index58 alt2">59</div><div class="line number60 index59 alt1">60</div><div class="line number61 index60 alt2">61</div><div class="line number62 index61 alt1">62</div><div class="line number63 index62 alt2">63</div><div class="line number64 index63 alt1">64</div><div class="line number65 index64 alt2">65</div><div class="line number66 index65 alt1">66</div><div class="line number67 index66 alt2">67</div><div class="line number68 index67 alt1">68</div><div class="line number69 index68 alt2">69</div><div class="line number70 index69 alt1">70</div><div class="line number71 index70 alt2">71</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java comments">//# Write texts to file using OutputStreamWriter specifying its charset encoding.</code></div><div class="line number3 index2 alt2"><code class="java comments">//# Read byte-by-byte using FileInputStream.</code></div><div class="line number4 index3 alt1"><code class="java comments">//# Read char-by-char using InputStreamReader specifying its charset encoding.</code></div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">TextFileEncodingJDK7 {</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String message = </code><code class="java string">"Hi,您好!"</code><code class="java plain">;&nbsp;&nbsp; </code><code class="java comments">//# with non-ASCII chars</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Java internally stores char in UCS-2/UTF-16</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print the characters stored with Hex codes</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; message.length(); i++) {</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">char</code> <code class="java plain">aChar = message.charAt(i);</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"[%d]'%c'(%04X) "</code><code class="java plain">, (i+</code><code class="java value">1</code><code class="java plain">), aChar, (</code><code class="java keyword">int</code><code class="java plain">)aChar);</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Try these charsets for encoding text file</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String[] csStrs = {</code><code class="java string">"UTF-8"</code><code class="java plain">, </code><code class="java string">"UTF-16BE"</code><code class="java plain">, </code><code class="java string">"UTF-16LE"</code><code class="java plain">, </code><code class="java string">"UTF-16"</code><code class="java plain">, </code><code class="java string">"GB2312"</code><code class="java plain">, </code><code class="java string">"GBK"</code><code class="java plain">, </code><code class="java string">"BIG5"</code><code class="java plain">};</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String outFileExt = </code><code class="java string">"-out.txt"</code><code class="java plain">;&nbsp;&nbsp; </code><code class="java comments">//# Output filenames are "charset-out.txt"</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write text file in the specified file encoding charset</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; csStrs.length; i++) {</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(OutputStreamWriter out =</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">OutputStreamWriter(</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(csStrs[i] + outFileExt), csStrs[i]);</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">BufferedWriter bufOut = </code><code class="java keyword">new</code> <code class="java plain">BufferedWriter(out)) {&nbsp; </code><code class="java comments">//# Buffered for efficiency</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(out.getEncoding());&nbsp; </code><code class="java comments">//# Print file encoding charset</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">bufOut.write(message);</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">bufOut.flush();</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read raw bytes from various encoded files</code></div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//#&nbsp;&nbsp; to check how the characters were encoded.</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; csStrs.length; i++) {</code></div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedInputStream in = </code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(&nbsp; </code><code class="java comments">//# Buffered for efficiency</code></div><div class="line number38 index37 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(csStrs[i] + outFileExt))) {</code></div><div class="line number39 index38 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%10s"</code><code class="java plain">, csStrs[i]);&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Print file encoding charset</code></div><div class="line number40 index39 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">inByte;</code></div><div class="line number41 index40 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((inByte = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number42 index41 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, inByte);&nbsp;&nbsp; </code><code class="java comments">//# Print Hex codes</code></div><div class="line number43 index42 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number44 index43 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number45 index44 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number46 index45 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number47 index46 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number48 index47 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number49 index48 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number50 index49 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read text file with character-stream specifying its encoding.</code></div><div class="line number51 index50 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# The char will be translated from its file encoding charset to</code></div><div class="line number52 index51 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//#&nbsp;&nbsp; Java internal UCS-2.</code></div><div class="line number53 index52 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; csStrs.length; i++) {</code></div><div class="line number54 index53 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(InputStreamReader in =</code></div><div class="line number55 index54 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">InputStreamReader(</code></div><div class="line number56 index55 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(csStrs[i] + outFileExt), csStrs[i]);</code></div><div class="line number57 index56 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">BufferedReader bufIn = </code><code class="java keyword">new</code> <code class="java plain">BufferedReader(in)) {&nbsp; </code><code class="java comments">//# Buffered for efficiency</code></div><div class="line number58 index57 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.getEncoding());&nbsp; </code><code class="java comments">//# print file encoding charset</code></div><div class="line number59 index58 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">inChar;</code></div><div class="line number60 index59 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">count = </code><code class="java value">0</code><code class="java plain">;</code></div><div class="line number61 index60 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((inChar = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number62 index61 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">count++;</code></div><div class="line number63 index62 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"[%d]'%c'(%04X) "</code><code class="java plain">, count, (</code><code class="java keyword">char</code><code class="java plain">)inChar, inChar);</code></div><div class="line number64 index63 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number65 index64 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number66 index65 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number67 index66 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number68 index67 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number69 index68 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number70 index69 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number71 index70 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>


<pre class="output">[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)
  
UTF-8:    48 69 2C <span class="underline">E6 82 A8 <span class="underline">E5 A5 BD 21
          <span class="color-comment">H  i  ,  您       好       !
UTF-16BE: 00 48 00 69 00 2C <span class="underline">60 A8 <span class="underline">59 7D 00 21
          <span class="color-comment">H     i     ,     您    好    !
UTF-16LE: 48 00 69 00 2C 00 <span class="underline">A8 60 <span class="underline">7D 59 21 00
          <span class="color-comment">H     i     ,     您    好    !
UTF-16:   FE FF 00 48 00 69 00 2C <span class="underline">60 A8 <span class="underline">59 7D 00 21
          <span class="color-comment">BOM   H     i     ,     您    好    !
GB2312:   48 69 2C <span class="underline">C4 FA <span class="underline">BA C3 21
          <span class="color-comment">H  i  ,  您    好    !
GBK:      48 69 2C <span class="underline">C4 FA <span class="underline">BA C3 21
          <span class="color-comment">H  i  ,  您    好    !
BIG5:     48 69 2C <span class="underline">B1 7A <span class="underline">A6 6E 21
          <span class="color-comment">H  i  ,  您    好    !
  
UTF8
[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)

UnicodeBigUnmarked <span class="color-comment">[UTF-16BE without BOM]
[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)

UnicodeLittleUnmarked <span class="color-comment">[UFT-16LE without BOM]
[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)

UTF-16
[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)

EUC_CN <span class="color-comment">[GB2312]
[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)

GBK
[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)

Big5
[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></pre>

<p>As seen from the output, the characters 您好 is encoded differently in different charsets. Nonetheless, the <code>InputStreamReader</code> is able to translate the characters into the same UCS-2 used in Java program.</p>

<h3><span class="font-code">java.io.PrintStream &amp; <span class="font-code">java.io.PrintWriter</span></span></h3>
<img class="image-float-right" src="AppKubos_files/IO_PrintStreamWriter.png">
<p>The byte-based <code>java.io.printSteam</code> supports convenient printing methods such as <code>print()</code> and <code>println()</code> for printing primitives and text string. Primitives are converted to their string representation for printing. The  <code>printf()</code> and <code>format()</code> were introduced in JDK 1.5 for formatting output with former specifiers. <code>printf()</code> and <code>format()</code> are identical.</p>

<p>A <code>PrintStream</code> never throws an <code>IOException</code>. Instead, it sets an internal flag which can be checked via the <code>checkError()</code> method. A <code>PrintStream</code> can also be created to flush the output automatically. That is, the <code>flush()</code> method is automatically invoked after a byte array is written, one of the <code>println(</code>) methods is invoked, or after a newline (<code>'\n'</code>) is written.</p>

<p>The standard output and error streams (<code>System.out</code> and <code>System.err</code>) belong to <code>PrintStream</code>.</p>

<p>All characters printed by a <code>PrintStream</code> are converted into bytes using the default character encoding. The <code>PrintWriter</code> class should be used in situations that require writing characters rather than bytes.</p>
<p>The character-stream <code>PrintWriter</code> is similar to <code>PrintStream</code>, except that it write in characters instead of bytes. The <code>PrintWriter</code> also supports all the convenient printing methods <code>print()</code>, <code>println()</code>, <code>printf()</code> and <code>format()</code>. It never throws an <code>IOException</code> and can optionally be created to support automatic flushing.</p>
<p>[TODO] Example to show the difference between <code>PrintStream</code> and <code>PrintWriter</code>.</p>

<h3>Object Serialization and Object Streams</h3>

<p>Data streams (<code>DataInputStream</code> and <code>DataOutputStream</code>) allow you to read and write primitive data (such as <code>int</code>, <code>double</code>) and <code>String</code>, rather than individual bytes. Object streams (<code>ObjectInputStream</code> and <code>ObjectOutputStream</code>) go one step further to allow you to read and write entire objects (such as <code>Date</code>, <code>ArrayList</code> or any custom objects).</p>

<p>Object serialization is the process of representing a "particular 
state of an object" in a serialized bit-stream, so that the bit stream 
can be written out to an external device (such as a disk file or 
network). The bit-stream can later be re-constructed to recover the 
state of that object.  Object serialization is necessary to save a state
 of an object into a disk file for persistence or sent the object across
 the network for applications such as Web Services, Distributed-object 
applications, and Remote Method Invocation (RMI).</p>

<p>In Java, object that requires to be serialized must implement <code>java.io.Serializable</code> or <code>java.io.Externalizable</code> interface.  <code>Serializable</code>
 interface is an empty interface (or tagged interface) with nothing 
declared.  Its purpose is simply to declare that particular object is 
serializable.</p>

<h4><span class="font-code">ObjectInputStream &amp; <span class="font-code">ObjectOutputStream</span></span></h4>

<p>The <code>ObjectInputStream</code> and <code>ObjectOutputStream</code> can be used to serialize an object into a bit-stream and transfer it to/from an I/O streams, via these methods:</p>
<div><div id="highlighter_478261" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java plain">Object readObject() </code><code class="java keyword">throws</code> <code class="java plain">IOException, ClassNotFoundException;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">final</code> <code class="java keyword">void</code> <code class="java plain">writeObject(Object obj) </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div></div></td></tr></tbody></table></div></div>

<p><code>ObjectInputStream</code> and <code>ObjectOutputStream</code> must be stacked on top of a concrete implementation of <code>InputStream</code> or <code>OutputStream</code>, such as <code>FileInputStream</code> or <code>FileOutputStream</code>.</p>

<p>For example, the following code segment writes objects to a disk file. The "<code>.ser</code>" is the convention for serialized object file type.</p>
<div><div id="highlighter_549332" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">ObjectOutputStream out =</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">ObjectOutputStream(</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedOutputStream(</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(</code><code class="java string">"object.ser"</code><code class="java plain">)));</code></div><div class="line number5 index4 alt2"><code class="java plain">out.writeObject(</code><code class="java string">"The current Date and Time is "</code><code class="java plain">); </code><code class="java comments">//# write a String object</code></div><div class="line number6 index5 alt1"><code class="java plain">out.writeObject(</code><code class="java keyword">new</code> <code class="java plain">Date());&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 </code><code class="java comments">//# write a Date object</code></div><div class="line number7 index6 alt2"><code class="java plain">out.flush();</code></div><div class="line number8 index7 alt1"><code class="java plain">out.close();</code></div></div></td></tr></tbody></table></div></div>

<p>To read and re-construct the object back in a program, use the method <code>readObject()</code>, which returns an <code>java.lang.Object</code>. Downcast the <code>Object</code> back to its original type.</p>
<div><div id="highlighter_653145" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">ObjectInputStream in = </code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">ObjectInputStream(</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(</code><code class="java string">"object.ser"</code><code class="java plain">)));</code></div><div class="line number5 index4 alt2"><code class="java plain">String str = (String)in.readObject();</code></div><div class="line number6 index5 alt1"><code class="java plain">Date d = (Date)in.readObject(</code><code class="java keyword">new</code> <code class="java plain">Date());&nbsp; </code><code class="java comments">//# downcast</code></div><div class="line number7 index6 alt2"><code class="java plain">in.close();</code></div></div></td></tr></tbody></table></div></div>

<p><span class="line-heading">Example: Object serialization</span></p>

<div><div id="highlighter_695542" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div><div class="line number39 index38 alt2">39</div><div class="line number40 index39 alt1">40</div><div class="line number41 index40 alt2">41</div><div class="line number42 index41 alt1">42</div><div class="line number43 index42 alt2">43</div><div class="line number44 index43 alt1">44</div><div class="line number45 index44 alt2">45</div><div class="line number46 index45 alt1">46</div><div class="line number47 index46 alt2">47</div><div class="line number48 index47 alt1">48</div><div class="line number49 index48 alt2">49</div><div class="line number50 index49 alt1">50</div><div class="line number51 index50 alt2">51</div><div class="line number52 index51 alt1">52</div><div class="line number53 index52 alt2">53</div><div class="line number54 index53 alt1">54</div><div class="line number55 index54 alt2">55</div><div class="line number56 index55 alt1">56</div><div class="line number57 index56 alt2">57</div><div class="line number58 index57 alt1">58</div><div class="line number59 index58 alt2">59</div><div class="line number60 index59 alt1">60</div><div class="line number61 index60 alt2">61</div><div class="line number62 index61 alt1">62</div><div class="line number63 index62 alt2">63</div><div class="line number64 index63 alt1">64</div><div class="line number65 index64 alt2">65</div><div class="line number66 index65 alt1">66</div><div class="line number67 index66 alt2">67</div><div class="line number68 index67 alt1">68</div><div class="line number69 index68 alt2">69</div><div class="line number70 index69 alt1">70</div><div class="line number71 index70 alt2">71</div><div class="line number72 index71 alt1">72</div><div class="line number73 index72 alt2">73</div><div class="line number74 index73 alt1">74</div><div class="line number75 index74 alt2">75</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">ObjectSerializationTest {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String filename = </code><code class="java string">"object.ser"</code><code class="java plain">;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">numObjs = </code><code class="java value">5</code><code class="java plain">;</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write objects</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(ObjectOutputStream out =</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">ObjectOutputStream(</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedOutputStream(</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(filename)))) {</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Create an array of 10 MySerializedObjects with ascending numbers</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">MySerializedObject[] objs = </code><code class="java keyword">new</code> <code class="java plain">MySerializedObject[numObjs];</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; numObjs; i++) {</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">objs[i] = </code><code class="java keyword">new</code> <code class="java plain">MySerializedObject(</code><code class="java value">0xAA</code> <code class="java plain">+ i); </code><code class="java comments">//# Starting at AA</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write the objects to file, one by one.</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; numObjs; i++) {</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeObject(objs[i]);</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write the entire array in one go.</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.writeObject(objs);</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.flush();</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read raws bytes and print in Hex</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedInputStream in =</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(filename))) {</code></div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">inByte;</code></div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((inByte = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, inByte);&nbsp;&nbsp; </code><code class="java comments">//# Print Hex codes</code></div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number38 index37 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%n%n"</code><code class="java plain">);</code></div><div class="line number39 index38 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number40 index39 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number41 index40 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number42 index41 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number43 index42 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read objects</code></div><div class="line number44 index43 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(ObjectInputStream in =</code></div><div class="line number45 index44 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">ObjectInputStream(</code></div><div class="line number46 index45 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code></div><div class="line number47 index46 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(filename)))) {</code></div><div class="line number48 index47 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read back the objects, cast back to its original type.</code></div><div class="line number49 index48 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">MySerializedObject objIn;</code></div><div class="line number50 index49 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; numObjs; i++) {</code></div><div class="line number51 index50 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">objIn = (MySerializedObject)in.readObject();</code></div><div class="line number52 index51 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(objIn.getNumber());</code></div><div class="line number53 index52 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number54 index53 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">MySerializedObject[] objArrayIn;</code></div><div class="line number55 index54 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">objArrayIn = (MySerializedObject[])in.readObject();</code></div><div class="line number56 index55 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(MySerializedObject o : objArrayIn) {</code></div><div class="line number57 index56 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(o.getNumber());</code></div><div class="line number58 index57 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number59 index58 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(ClassNotFoundException|IOException ex) {&nbsp; </code><code class="java comments">//# JDK 7</code></div><div class="line number60 index59 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number61 index60 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number62 index61 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number63 index62 alt2"><code class="java plain">}</code></div><div class="line number64 index63 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number65 index64 alt2"><code class="java keyword">class</code> <code class="java plain">MySerializedObject </code><code class="java keyword">implements</code> <code class="java plain">Serializable {</code></div><div class="line number66 index65 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">private</code> <code class="java keyword">int</code> <code class="java plain">number;</code></div><div class="line number67 index66 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number68 index67 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java plain">MySerializedObject(</code><code class="java keyword">int</code> <code class="java plain">number) {</code></div><div class="line number69 index68 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">this</code><code class="java plain">.number = number;</code></div><div class="line number70 index69 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number71 index70 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number72 index71 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">getNumber() {</code></div><div class="line number73 index72 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">return</code> <code class="java plain">number;</code></div><div class="line number74 index73 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number75 index74 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">AC ED 00 05 73 72 00 12 4D 79 53 65 72 69 61 6C 69 7A 65 64 4F 62 6A 65 
63 74 1F 7B 91 BD 02 1C DC 30 02 00 01 49 00 06 6E 75 6D 62 65 72 78 70 
<span class="underline">00 00 00 AA 73 71 00 7E 00 00 <span class="underline">00 00 00 AB 73 71 00 7E 00 00 <span class="underline">
00 00 00 AC 73 71 00 7E 00 00 <span class="underline">00 00 00 AD 73 71 00 7E 00 00 
<span class="underline">00 00 00 AE 75 72 00 15 5B 4C 4D 79 53 65 72 69 61 6C 69 7A 65 64 4F 62 
6A 65 63 74 3B 13 95 A0 51 BC 86 75 38 02 00 00 78 70 00 00 00 05 71 00 
7E 00 01 71 00 7E 00 02 71 00 7E 00 03 71 00 7E 00 04 71 00 7E 00 05</span></span></span></span></span></pre>

<p>[Check out these bytes!]</p>

<p>Primitive types and array are, by default, serializable.</p>

<p>The <code>ObjectInputStream</code> and <code>ObjectOutputStream</code> implement <code>DataInput</code> and <code>DataOutput</code> interface respectively.  You can used methods such as <code>readInt()</code>, <code>readDouble()</code>, <code>writeInt()</code>, <code>writeDouble()</code> for reading and writing primitive types.</p>

<h5><span class="font-code">transient &amp; <span class="font-code">static</span></span></h5>

<ul>
<li><code>static</code> fields are not serialized, as it belongs to the class instead of the particular instance to be serialized.</li>
<li>To prevent certain fields from being serialized, mark them using the keyword <code>transient</code>.  This could cut down the amount of data traffic.</li>
<li>The <code>writeObject()</code> method writes out the class of the object, the class signature, and values of non-<code>static</code> and non-<code>transient</code> fields.</li>
</ul>

<h4><span class="font-code">java.io.Serializable &amp; <span class="font-code">Externalizable Interfaces</span></span></h4>

<p>When you create a class that might be serialized, the class must implement <code>java.io.Serializable</code> interface. The <code>Serializable</code> interface doesn't declare any methods. Empty interfaces such as <code>Serializable</code>
 are known as tagging interfaces. They identify implementing classes as 
having certain properties, without requiring those classes to actually 
implement any methods.</p>

<p>Most of the core Java classes implement <code>Serializable</code>, 
such as all the wrapper classes, collection classes, and GUI classes. In
 fact, the only core Java classes that do not implement <code>Serializable</code> are ones that should not be serialized. Arrays of primitives or serializable objects are themselves serializable.</p>
<h5>Warning Message "The serialization class does not declare a static final serialVersionUID field of type long" (Advanced)</h5>

<p>This warning message is triggered because your class (such as <code>java.swing.JFrame</code>) implements the <code>java.io.Serializable</code> interface. This interface enables the object to be written out to an output stream serially (via method <code>writeObject()</code>); and read back into the program (via method <code>readObject()</code>). The serialization runtime uses a number (called <code>serialVersionUID</code>)
 to ensure that the object read into the program (during 
deserialization) is compatible with the class definition, and not 
belonging to another version. It throws an <code>InvalidClassException</code> otherwise.</p>

<p>You have these options:</p>
<ol>
<li>Simply ignore this warning message. If a <code>serializable</code> class does not explicitly declare a <code>serialVersionUID</code>, then   the serialization runtime will calculate a default <code>serialVersionUID</code> value   for that class based on various aspects of the class.</li>
<li>Add a <code>serialVersionUID</code> (Recommended), e.g.
  <div><div id="highlighter_674817" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">private</code> <code class="java keyword">static</code> <code class="java keyword">final</code> <code class="java keyword">long</code> <code class="java plain">serialVersionUID = 1L;&nbsp; </code><code class="java comments">//# verion 1</code></div></div></td></tr></tbody></table></div></div></li>

<li>Suppress this particular warning via annotation <code>@SuppressWarmomgs</code> (in package <code>java.lang</code>) (JDK 1.5):
<div><div id="highlighter_223821" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java color1">@SuppressWarnings</code><code class="java plain">(</code><code class="java string">"serial"</code><code class="java plain">)</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">MyFrame </code><code class="java keyword">extends</code> <code class="java plain">JFrame { ...... }</code></div></div></td></tr></tbody></table></div></div>
</li>
</ol>

<h5><span class="font-code">java.io.Externalizable Interface</span></h5>

<p>The <code>Serializable</code> has a sub-interface called <code>Externalizable</code>, which you could used if you want to customize the way a class is serialized. Since <code>Externalizable</code> extends <code>Serializable</code>, it is also a <code>Serializable</code> and you could invoke <code>readObject()</code> and <code>writeObject()</code>.</p>

<p><code>Externalizable</code> declares two <code>abstract</code> methods:</p>

<div><div id="highlighter_221920" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">void</code> <code class="java plain">writeExternal(ObjectOutput out) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java keyword">void</code> <code class="java plain">readExternal(ObjectInput in) </code><code class="java keyword">throws</code> <code class="java plain">IOException, ClassNotFoundException</code></div></div></td></tr></tbody></table></div></div>

<p><code>ObjectOutput</code> and <code>ObjectInput</code> are interfaces that are implemented by <code>ObjectOutputStream</code> and <code>ObjectInputStream</code>, which define the <code>writeObject()</code> and <code>readObject()</code> methods, respectively. When an instance of <code>Externalizable</code> is passed to an <code>ObjectOutputStream</code>, the default serialization procedure is bypassed; instead, the stream calls the instance's <code>writeExternal()</code> method. Similarly, when an <code>ObjectInputStream</code> reads a <code>Exteranlizabled</code> instance, it uses <code>readExternal()</code> to reconstruct the instance.</p>

<p><code></code><code>Externalizable</code> is useful if you want 
complete control on how your objects shall be serialized/deserialized. 
For example, you could encrypt sensitive data before the object is 
serialized.</p>

<h3>Random Access Files</h3>

<p>All the I/O streams covered so far are one-way streams.  That is, 
they are either read-only input stream or write-only output stream.  
Furthermore, they are all sequential-access (or serial) streams, meant 
for reading and writing data sequentially.  Nonetheless, it is sometimes
 necessary to read a file record directly as well as modifying existing 
records or inserting new records.  The class <code>RandomAccessFile</code> provides supports for non-sequential, direct (or random) access to a disk file.  <code>RandomAccessFile</code> is a two-way stream, supporting both input and output operations in the same stream.</p>

<p><code>RandomAccessFile</code> can be treated as a huge byte array.  You can use a file pointer (of type <code>long</code>),
 similar to array index, to access individual byte or group of bytes in 
primitive types (such as int and double).  The file pointer is located 
at 0 when the file is opened.  It advances automatically for every read 
and write operation by the number of bytes processed.</p>

<img class="image-center" src="AppKubos_files/IO_RandomAccessFile.htm">

<p>In constructing a <code>RandomAccessFile</code>, you can use flags <code>'r'</code> or <code>'rw'</code> to indicate whether the file is "read-only" or "read-write" access, e.g.,</p>
<div><div id="highlighter_827279" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">RandomAccessFile f1 = </code><code class="java keyword">new</code> <code class="java plain">RandomAccessFile(</code><code class="java string">"filename"</code><code class="java plain">, </code><code class="java string">"r"</code><code class="java plain">);</code></div><div class="line number2 index1 alt1"><code class="java plain">RandomAccessFile f2 = </code><code class="java keyword">new</code> <code class="java plain">RandomAccessFile(</code><code class="java string">"filename"</code><code class="java plain">, </code><code class="java string">"rw"</code><code class="java plain">);</code></div></div></td></tr></tbody></table></div></div>

<p>The following methods are available:</p>

<div><div id="highlighter_308569" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">seek(</code><code class="java keyword">long</code> <code class="java plain">pos) </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number2 index1 alt1"><code class="java comments">//# Positions the file pointer for subsequent read/write operation.</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">skipBytes(</code><code class="java keyword">int</code> <code class="java plain">numBytes) </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number4 index3 alt1"><code class="java comments">//# Moves the file pointer forward by the specified number of bytes.</code></div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java keyword">long</code> <code class="java plain">getFilePointer() </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number6 index5 alt1"><code class="java comments">//# Gets the position of the current file pointer, in bytes, from the beginning of the file.</code></div><div class="line number7 index6 alt2"><code class="java keyword">public</code> <code class="java keyword">long</code> <code class="java plain">length() </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number8 index7 alt1"><code class="java comments">//# Returns the length of this file.</code></div></div></td></tr></tbody></table></div></div>

<p><code>RandomAccessFile</code> does not inherit from <code>InputStream</code> or <code>OutputStream</code>. However, it implements <code>DataInput</code> and <code>DataOutput</code> interfaces (similar to <code>DataInputStream</code> and <code>DataOutputStream</code>).  Therefore, you can use various methods to read/write primitive types to the file, e.g.,</p>
<div><div id="highlighter_633487" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">readInt() </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">double</code> <code class="java plain">readDouble() </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">writeInt(</code><code class="java keyword">int</code> <code class="java plain">i) </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">writeDouble(</code><code class="java keyword">double</code> <code class="java plain">d) </code><code class="java keyword">throws</code> <code class="java plain">IOException;</code></div></div></td></tr></tbody></table></div></div>

<p><span class="line-heading">Example: Read and write records from a <code>RandomAccessFile</code>. (A student file consists of student record of name (<code>String</code>) and id (<code>int</code>)).</span></p>
<p>[PENDING]</p>

<h3>Compressed I/O Streams</h3>
<p>The classes <code>ZipInputStream</code> and <code>ZipOutputStream</code> (in package <code>java.util</code>) support reading and writing of compressed data in ZIP format.  The classes <code>GZIPInputStream</code> and <code>GZIPOutputStream</code> (in package <code>java.util</code>) support reading and writing of compressed data in GZIP format.</p>

<p><span class="line-heading">Example: Reading and writing ZIP files</span></p>
<p>[@PENDING]</p>

<p><span class="line-heading">Example: Reading and writing JAR files</span></p>
<p>[@PENDING]</p>

<h3 id="formattedtextio">Formatted Text I/O - <span class="font-code">java.util.Scanner &amp; <span class="font-code">java.util.Formatter (JDK 1.5)</span></span></h3>

<h4>Formatted-Text Input via <span class="font-code">java.util.Scanner</span></h4>

<p>JDK 1.5 introduces <code>java.util.Scanner</code> class, which greatly simplifies formatted text input from input source (e.g., files, keyboard, network).  <code>Scanner</code>,
 as the name implied, is a simple text scanner which can parse the input
 text into primitive types and strings using regular expressions. It 
first breaks the text input into tokens using a delimiter pattern, which
 is by default the white spaces (blank, tab and newline).  The tokens 
may then be converted into primitive values of different types using the
 various <code>nextXxx()</code> methods (<code>nextInt()</code>, <code>nextByte()</code>, <code>nextShort()</code>, <code>nextLong()</code>, <code>nextFloat()</code>, <code>nextDouble()</code>, <code>nextBoolean()</code>, <code>next()</code> for <code>String</code>, and <code>nextLine()</code> for an input line). You can also use the <code>hasNextXxx()</code> methods to check for the availability of a desired input.</p>

<p>The commonly-used constructors are as follows. You can construct a <code>Scanner</code> to parse a byte-based <code>InputStream</code> (e.g., <code>System.in</code>), a disk file, or a given <code>String</code>.</p>

<div><div id="highlighter_25855" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# Scanner piped from a disk File</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">Scanner(File source) </code><code class="java keyword">throws</code> <code class="java plain">FileNotFoundException</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java plain">Scanner(File source, String charsetName) </code><code class="java keyword">throws</code> <code class="java plain">FileNotFoundException</code></div><div class="line number4 index3 alt1"><code class="java comments">//# Scanner piped from a byte-based InputStream, e.g., System.in</code></div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java plain">Scanner(InputStream source)</code></div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java plain">Scanner(InputStream source, String charsetName)</code></div><div class="line number7 index6 alt2"><code class="java comments">//# Scanner piped from the given source string (NOT filename string)</code></div><div class="line number8 index7 alt1"><code class="java keyword">public</code> <code class="java plain">Scanner(String source)</code></div></div></td></tr></tbody></table></div></div>

<p>For examples,</p>


<div><div id="highlighter_502268" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# Construct a Scanner to parse an int from keyboard</code></div><div class="line number2 index1 alt1"><code class="java plain">Scanner in1 = </code><code class="java keyword">new</code> <code class="java plain">Scanner(System.in);</code></div><div class="line number3 index2 alt2"><code class="java keyword">int</code> <code class="java plain">i = in1.nextInt();</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number5 index4 alt2"><code class="java comments">//# Construct a Scanner to parse all doubles from a disk file</code></div><div class="line number6 index5 alt1"><code class="java plain">Scanner in2 = </code><code class="java keyword">new</code> <code class="java plain">Scanner(</code><code class="java keyword">new</code> <code class="java plain">File(</code><code class="java string">"in.txt"</code><code class="java plain">));&nbsp; </code><code class="java comments">//# need to handle FileNotFoundException</code></div><div class="line number7 index6 alt2"><code class="java keyword">while</code> <code class="java plain">(in2.hasNextDouble()) {</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">double</code> <code class="java plain">d = in.nextDouble();</code></div><div class="line number9 index8 alt2"><code class="java plain">}</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number11 index10 alt2"><code class="java comments">//# Construct a Scanner to parse a given text string</code></div><div class="line number12 index11 alt1"><code class="java plain">Scanner in3 = </code><code class="java keyword">new</code> <code class="java plain">Scanner(</code><code class="java string">"This is the input text String"</code><code class="java plain">);</code></div><div class="line number13 index12 alt2"><code class="java keyword">while</code> <code class="java plain">(in3.hasNext()) {</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">String s = in.next();</code></div><div class="line number15 index14 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<p><span class="line-heading">Example 1: The most common usage of <code>Scanner</code> is to read primitive types and <code>String</code> form the keyboard (<code>System.in</code>), as follows:</span></p>

<div><div id="highlighter_805908" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.util.Scanner;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">TestScannerSystemIn {</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Scanner in = </code><code class="java keyword">new</code> <code class="java plain">Scanner(System.in);</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"Enter an integer: "</code><code class="java plain">);</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">anInt = in.nextInt();</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"You entered "</code> <code class="java plain">+ anInt);</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"Enter a floating-point number: "</code><code class="java plain">);</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">double</code> <code class="java plain">aDouble = in.nextDouble();</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"You entered "</code> <code class="java plain">+ aDouble);</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"Enter 2 words: "</code><code class="java plain">);</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String word1 = in.next();&nbsp; </code><code class="java comments">//# read a string delimited by white space</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String word2 = in.next();&nbsp; </code><code class="java comments">//# read a string delimited by white space</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"You entered "</code> <code class="java plain">+ word1 + </code><code class="java string">" "</code> <code class="java plain">+ word2);</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">in.nextLine();&nbsp;&nbsp; </code><code class="java comments">//# flush the "enter" before the next readLine()</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"Enter a line: "</code><code class="java plain">);</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String line = in.nextLine();&nbsp; </code><code class="java comments">//# read a string up to line delimiter</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"You entered "</code> <code class="java plain">+ line);</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number25 index24 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<p>The <code>nextXxx()</code> methods throw <code>InputMismatchException</code> if the next token does not match the type to be parsed.</p>

<p><span class="line-heading">Example 2: You can easily modify the above program to read the inputs from a text file, instead of keyboard (<code>System.in</code>).</span></p>

<div><div id="highlighter_262984" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.util.Scanner;</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">TestScannerFile {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) </code><code class="java keyword">throws</code> <code class="java plain">FileNotFoundException {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Scanner in = </code><code class="java keyword">new</code> <code class="java plain">Scanner(</code><code class="java keyword">new</code> <code class="java plain">File(</code><code class="java string">"in.txt"</code><code class="java plain">));</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"Enter an integer: "</code><code class="java plain">);</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">anInt = in.nextInt();</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"You entered "</code> <code class="java plain">+ anInt);</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"Enter a floating-point number: "</code><code class="java plain">);</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">double</code> <code class="java plain">aDouble = in.nextDouble();</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"You entered "</code> <code class="java plain">+ aDouble);</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"Enter 2 words: "</code><code class="java plain">);</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String word1 = in.next();&nbsp; </code><code class="java comments">//# read a string delimited by white space</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String word2 = in.next();&nbsp; </code><code class="java comments">//# read a string delimited by white space</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"You entered "</code> <code class="java plain">+ word1 + </code><code class="java string">" "</code> <code class="java plain">+ word2);</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">in.nextLine();&nbsp;&nbsp; </code><code class="java comments">//# flush the "enter" before the next readLine()</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.print(</code><code class="java string">"Enter a line: "</code><code class="java plain">);</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String line = in.nextLine();&nbsp; </code><code class="java comments">//# read a string up to line delimiter</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"You entered "</code> <code class="java plain">+ line);</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number26 index25 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>
<p>Prepare the input file "<code>in.txt</code>" as follows:</p>

<pre class="output">123
44.55
first second
this is a test</pre>

<h5><span class="font-code">nextXxx() and <span class="font-code">hasNextXxx()</span></span></h5>

<p>The <code>Scanner</code> class implements <code>iterator&lt;String&gt;</code> interface.  You can use <code>hasNext()</code> coupled with <code>next()</code> to iterate through all the <code>String</code> tokens.  You can also directly iterate through the primitive types via methods <code>hasNextXxx()</code> and <code>nextXxx()</code>. <code>Xxx</code> includes all primitive types (<code>byte</code>, <code>short</code>, <code>int</code>, <code>long</code>, <code>float</code>, <code>double</code> and <code>boolean</code>), <code>BigInteger,</code> and <code>BigNumber</code>. <code>char</code> is not included but can be retrieved from <code>String</code> via <code>charAt()</code>.</p>

<h5>Delimiter</h5>

<p>Instead of the default white spaces as the delimiter, you can set the
 delimiter to a chosen regular expression via these methods:</p>
<div><div id="highlighter_559561" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java plain">Pattern delimiter()&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Returns the current delimiter Regexe Pattern</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">Scanner useDelimiter(Pattern pattern)&nbsp;&nbsp; </code><code class="java comments">//# Sets the delimiter Regexe Pattern</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java plain">Scanner useDelimiter(String pattern)</code></div></div></td></tr></tbody></table></div></div>

<p><span class="line-heading">Example 3: Customized token delimiter</span></p>
<div><div id="highlighter_969179" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.util.Scanner;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">ScannerWithDelimiter {</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Scanner in = </code><code class="java keyword">new</code> <code class="java plain">Scanner(</code><code class="java string">"one apple 2 apple red apple big apple 5.5 apple"</code><code class="java plain">);</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Zero or more whitespace, followed by 'apple', followed by zero or more whitespace.</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">in.useDelimiter(</code><code class="java string">"\\s*apple\\s*"</code><code class="java plain">);</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# The delimiter breaks the input into tokens {"one", "2", "red", "big", "5.5"}.</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.next());</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.nextInt());&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# parses text into int</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.next());</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.next());</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.nextDouble());&nbsp;&nbsp; </code><code class="java comments">//# parses text into double</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number14 index13 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<p>The regular expression <code>\s*apple\s*</code> matches zero or more white spaces (<code>\s*</code>) followed by "apple" followed by zero or more white spaces (<code>\s*</code>). An additional backslash (<code>\</code>) is needed to use a backslash (<code>\</code>) in Java <code>String</code>'s literal. Read "<a href="file:///d:/myweb/programming/howto/Regexe.html">Regular Expression</a>" for more details.</p>

<h5>Regexe Pattern Matching</h5>

<p>You can use the following methods to find the next occurrence of the specified pattern using regular expressions:</p>
<div><div id="highlighter_649267" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# Find the next occurrence of a pattern, ignoring delimiters</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">String findInLine(Pattern pattern)</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java plain">String findInLine(String pattern)</code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java plain">String findWithinHorizon(Pattern pattern, </code><code class="java keyword">int</code> <code class="java plain">horizon)</code></div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java plain">String findWithinHorizon(String pattern, </code><code class="java keyword">int</code> <code class="java plain">horizon)</code></div><div class="line number6 index5 alt1"><code class="java comments">//# Skips input that matches the specified pattern, ignoring delimiters</code></div><div class="line number7 index6 alt2"><code class="java keyword">public</code> <code class="java plain">Scanner skip(Pattern pattern)</code></div><div class="line number8 index7 alt1"><code class="java keyword">public</code> <code class="java plain">Scanner skip(String pattern)</code></div></div></td></tr></tbody></table></div></div>

<h5>Charset</h5>
<p>By default, <code>Scanner</code> uses the default charset to read the character from the input source. You can ask <code>Scanner</code> to read text file which is encoded using a particular charset, by providing the charset name.</p>

<p><span class="line-heading">Example 4:</span></p>

<div><div id="highlighter_414811" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div><div class="line number39 index38 alt2">39</div><div class="line number40 index39 alt1">40</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.util.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">TestScannerTextFile {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) </code><code class="java keyword">throws</code> <code class="java plain">FileNotFoundException {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String filename = </code><code class="java string">"test_scanner.txt"</code><code class="java plain">;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String message = </code><code class="java string">"Hi,您好!\n"</code><code class="java plain">;&nbsp;&nbsp; </code><code class="java comments">//# with non-ASCII chars</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Create a Text file in UTF-8</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">// Can also use formatter (see below)</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedWriter out =</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedWriter(</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">OutputStreamWriter(</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileOutputStream(filename), </code><code class="java string">"UTF-8"</code><code class="java plain">))) {</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(</code><code class="java string">"12345 55.66\n"</code><code class="java plain">);</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(message);</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.flush();</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read raws bytes and print in Hex</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedInputStream in =</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(filename))) {</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">inByte;</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((inByte = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, inByte);&nbsp;&nbsp; </code><code class="java comments">//# Print Hex codes</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Open a text file, specifying the charset for the file encoding</code></div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">&lt;span </code><code class="java keyword">class</code><code class="java plain">=</code><code class="java string">"color-new"</code><code class="java plain">&gt;Scanner in = </code><code class="java keyword">new</code> <code class="java plain">Scanner(</code><code class="java keyword">new</code> <code class="java plain">File(filename), </code><code class="java string">"UTF-8"</code><code class="java plain">);</code></div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.nextInt());</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.nextFloat());</code></div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">in.nextLine();&nbsp; </code><code class="java comments">//# Flush a newline</code></div><div class="line number38 index37 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.nextLine());</code></div><div class="line number39 index38 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number40 index39 alt1"><code class="java plain">}&lt;/span&gt;</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">31 32 33 34 35 20 35 35 2E 36 36 0A 48 69 2C E6 82 A8 E5 A5 BD 21 0A
<span class="color-comment">1  2  3  4  5  SP 5  5  .  6  6  LF H  i  ,  您       好       !  LF [UTF-8]

12345
55.66
Hi,您好!</span></pre>

<h4>Formatted-Text Printing with <span class="font-code">printf() method</span></h4>

<p>JDK 1.5 introduces C-like <code>printf()</code> method (in classes <code>java.io.PrintSteam</code> and <code>java.io.PrintWriter</code>) for formatted-text printing.</p>

<p>To write formatted-text to console (<code>System.out</code> or <code>System.err</code>), you could simply use the convenience methods <code>System.out.printf()</code> or <code>System.out.format()</code>. <code>printf()</code> takes this syntax:</p>
<div><div id="highlighter_76635" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java plain">PrintStream|PrintWriter printf(String formatSpecifier, Object... args)</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">PrintStream|PrintWriter printf(Locale locale, String formatSpecifier, Object... args)</code></div></div></td></tr></tbody></table></div></div>

<p><code>printf()</code> takes a variable number (zero or more) of 
arguments (or varargs). Varargs was introduced in JDK 1.5 (that is the 
reason Java cannot support <code>printf()</code> earlier).</p>

<p><code>printf()</code> can be called from <code>System.out</code> or <code>System.err</code> ( which are <code>PrintStream</code>s). For example,</p>
<div><div id="highlighter_483868" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">System.out.printf(</code><code class="java string">"Hello %4d %6.2f %s, and%n&nbsp;&nbsp; Hello again%n"</code><code class="java plain">, </code><code class="java value">123</code><code class="java plain">, </code><code class="java value">5.5</code><code class="java plain">, </code><code class="java string">"Hello"</code><code class="java plain">);</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">Hello  123   5.50 Hello, and
   Hello again</pre>
   
<p>You can also use the <code>System.out.format()</code> method, which is identitical to <code>System.out.printf()</code>.</p>

<h5>Format Specifiers</h5>
<p>A format specifier begins with <code>'%'</code> and ends with a conversion-type character (e.g. <code>"%d"</code> for integer, <code>"%f"</code> for <code>float</code> and <code>double</code>), with optional parameters in between, as follows:</p>
<div><div id="highlighter_263358" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">%[argument_position$][flag(s)][width][.precision]conversion-type-character</code></div></div></td></tr></tbody></table></div></div>

<ul>
<li>The optional argument_position specifies the position of the argument in the argument list.  The first argument is <code>"1$"</code>, second argument is <code>"2$"</code>, and so on.</li>
<li>The optional width indicates the minimum number of characters to be output.</li>
<li>The optional precision restricts the number of characters (or number of decimal places for float-point numbers).</li>
<li>The mandatory conversion-type-character indicates how the argument should be formatted.  For examples: <code>'b'</code>, <code>'B'</code> (<code>boolean</code>), <code>'h'</code>, <code>'H'</code> (hex string), <code>'s'</code>, <code>'S'</code> (string), <code>'c'</code>, <code>'C'</code> (character), <code>'d'</code> (decimal integer), <code>'o'</code> (octal integer), <code>'x'</code>, <code>'X'</code> (hexadecimal integer), <code>'e'</code>, <code>'E'</code> (float-point number in scientific notation), <code>'f'</code> (floating-point number), <code>'%'</code> (percent sign). The uppercase conversion code (e.g., <code>'S'</code>) formats the texts in uppercase.</li>
<li>Flag: <code>'-'</code> (left-justified), <code>'+'</code> (include sign), <code>' '</code> (include leading space), <code>'0'</code> (zero-padded), <code>','</code> (include grouping separator). <code>'('</code> (negative value in parentheses), <code>'//#'</code> (alternative form).</li>
</ul>

<p>Read JDK API <code>java.util.Formatter</code>'s "<a href="http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html//#syntax">Format String Syntax</a>" for details on format specifiers.</p>

<h5>Examples</h5>

<div><div id="highlighter_207452" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">System.out.printf(</code><code class="java string">"%2$2d %3$2d %1$2d%n"</code><code class="java plain">, </code><code class="java value">1</code><code class="java plain">, </code><code class="java value">12</code><code class="java plain">, </code><code class="java value">123</code><code class="java plain">, </code><code class="java value">1234</code><code class="java plain">);</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">12 123  1</pre>

<div><div id="highlighter_300270" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">System.out.printf(Locale.FRANCE, </code><code class="java string">"e = %+10.4f%n"</code><code class="java plain">, Math.PI);</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">e =    +3,1416</pre>

<div><div id="highlighter_258398" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">System.out.printf(</code><code class="java string">"Revenue: $ %(,.2f, Profit: $ %(,.2f%n"</code><code class="java plain">, </code><code class="java value">12345.6</code><code class="java plain">, -</code><code class="java value">1234.5678</code><code class="java plain">);</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">Revenue: $ 12,345.60, Profit: $ (1,234.57)</pre>

<h4>Formatted-Text Output via <span class="font-code">java.util.Formatter Class &amp; <span class="font-code">format() method</span></span></h4>
<p>JDK 1.5 introduced <code>java.util.Scanner</code> for formatted text input. It also introduced <code>java.util.Formatter</code> for formatted text output. </p>
<p>A <code>Formatter</code> is an interpreter for <code>printf</code>-style
   format strings. It supports layout justification and alignment, 
common   formats for numeric, string,   and date/time data, and 
locale-specific   output, via the format specifiers.</p>

<p>The <code>Formatter</code> has the following constructors:</p>

<div><div id="highlighter_837629" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java plain">Formatter(Appendable a);&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# StringBuffer and StringBuilder implement Appendable</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">Formatter(Appendable a, Locale l);</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java plain">Formatter(String filename)</code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java plain">Formatter(String fileName, String charsetName)</code></div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java plain">Formatter(File file)</code></div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java plain">Formatter(File file, String charsetName)</code></div><div class="line number7 index6 alt2"><code class="java keyword">public</code> <code class="java plain">Formatter(OutputStream os)</code></div><div class="line number8 index7 alt1"><code class="java keyword">public</code> <code class="java plain">Formatter(PrintStream ps)</code></div></div></td></tr></tbody></table></div></div>

<p><code>Formatter</code> supports <code>StringBuffer</code>/<code>StringBuilder</code> (as <code>Appendable</code>) as output sink. It does not support <code>String</code>, probably because <code>String</code> is immutable.</p>

<p>The <code>format()</code> method can be used to write formatted text output:</p>
<div><div id="highlighter_618043" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java plain">Formatter format(String formatSpecifier, Object... args)</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java plain">Formatter format(Locale locale, String formatSpecifier, Object... args)</code></div></div></td></tr></tbody></table></div></div>

<p>Notice that the method <code>format()</code> has the same syntax as the method <code>printf()</code>, using the same set of format specifier as <code>printf()</code>.</p>

<p>Other methods are:</p>
<div><div id="highlighter_836578" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">flush()&nbsp;&nbsp; </code><code class="java comments">//# flush out all the buffered output</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">close()</code></div></div></td></tr></tbody></table></div></div>

<p><span class="line-heading">Example 1: Using a <code>StringBuilder</code> (which implements <code>Appendable</code>) as the output sink for the <code>Formatter</code>.</span></p>

<table class="table-program">
<colgroup><col class="col-line-number">
<col class="col-program">
</colgroup><tbody>
<tr>
<td>
<pre class="text-right">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25</pre>
</td>
<td>
<pre>import java.util.Formatter;
import java.util.Locale;
 
public class TestFormatter {
   public static void main(String[] args) {
 
   //# Use a StringBuilder (Appandable) as the output sink for the Formatter
   StringBuilder sb = new StringBuilder();
   Formatter formatter = new Formatter(sb, Locale.US);
 
   //# Re-order output.
   formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d");
   System.out.println(sb);    //# -&gt; " d  c  b  a"
 
   //# Use the optional locale as the first argument.
   sb.delete(0, sb.length());
   formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);
   System.out.println(sb);    //# -&gt; "e =    +2,7183"
 
   //# Try negative number with '(' flag and group separator.
   sb.delete(0, sb.length());
   formatter.format("Net gained or lost: $ %(,.2f", -1234.567);
   System.out.println(sb);    //# -&gt; "Net gained or lost: $ (1,234.57)"
   }
}</pre>
</td>
</tr>
</tbody>
</table>

<p>Read JDK API <code>java.util.Formatter</code>'s "<a href="http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html//#syntax">Format String Syntax</a>" for details on format specifiers.</p>



<p><span class="line-heading">Example 2: Setting the charset for <code>Formatter</code>'s output.</span></p>

<div><div id="highlighter_163110" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div><div class="line number39 index38 alt2">39</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.util.*;</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">FormatterTest {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String filename = </code><code class="java string">"formatter-out.txt"</code><code class="java plain">;</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String message = </code><code class="java string">"Hi,您好!"</code><code class="java plain">;</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Create a text file in "UTF-8"</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(Formatter out = </code><code class="java keyword">new</code> <code class="java plain">Formatter(filename, </code><code class="java string">"UTF-8"</code><code class="java plain">)) {</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.format(</code><code class="java string">"%4d %6.2f %s%n"</code><code class="java plain">, </code><code class="java value">0xAA</code><code class="java plain">, </code><code class="java value">55.66</code><code class="java plain">, message);</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.flush();</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(UnsupportedEncodingException|FileNotFoundException ex) {</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read raws bytes and print in Hex</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedInputStream in =</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">FileInputStream(filename))) {</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">inByte;</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((inByte = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, inByte);&nbsp;&nbsp; </code><code class="java comments">//# Print Hex codes</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Set up text file input using a scanner and read records</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(Scanner in = </code><code class="java keyword">new</code> <code class="java plain">Scanner(</code><code class="java keyword">new</code> <code class="java plain">File(filename), </code><code class="java string">"UTF-8"</code><code class="java plain">)) {</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.nextInt());</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.nextDouble());</code></div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(in.next());</code></div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(FileNotFoundException ex) {</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number38 index37 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number39 index38 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">20 31 37 30 20 20 35 35 2E 36 36 20 48 69 2C E6 82 A8 E5 A5 BD 21 0A
<span class="color-comment">170         SP 55.66             SP H  i  ,  您       好       !  LF

170
55.66
Hi,您好!</span></pre>

<h4><span class="font-code">String.format()</span></h4>

<p>The <code>Formatter</code> with <code>StringBuilder</code> as the output sink allows you to build up a formatted string progressively. To produce a simple formatted <code>String</code>, you can simply use the <code>static</code> method <code>String.format()</code>. This is handy in the <code>toString()</code> method, which is required to return a <code>String</code>. For example,</p>

<table class="table-program">
<colgroup><col class="col-line-number">
<col class="col-program">
</colgroup><tbody>
<tr>
<td>
<pre class="text-right">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20</pre>
</td>
<td>
<pre>public class Time {
   private int hour, minute, second;
 
   public Time(int hour, int minute, int second) {
      this.hour = hour;
      this.minute = minute;
      this.second = second;
   }
 
   //# Returns a description in "HH:MM:SS"
   public String toString() {
      return <span class="color-new">String.format("%02d:%02d:%02d", hour, minute, second);
   }
 
   //# Test main()
   public static void main(String[] args) {
      Time t = new Time(1, 2, 3);
      System.out.println(t);   //# 01:02:03
   }
}</span></pre>
</td>
</tr>
</tbody>
</table>

<h3 id="jdk7io">File I/O in JDK 1.7</h3>

<p>[This section was extracted from the Java Online Tutorial and JDK 7 API.]</p>
<p>JDK 1.7 greatly enhances supports for file I/O via new package <code>java.nio.file</code> and its associated packages.</p>

<h4>Interface <span class="font-code">java.nio.file.Path</span></h4>

<p>A path string could be used to locate a file, a directory or a 
symbolic link. A symbolic link (or symlink) is a special file that 
references another file. A path string is system dependent, e.g., "<code>c:\myproject\java\Hello.java</code>" in Windows or "<code>/myproject/java/Hello.java</code>" in Unix. Windows uses back-slash <code>'\'</code> as the directory separator; while Unixes use forward-slash <code>'/'</code>. Windows uses semi-colon <code>';'</code> as path separator; while Unixes use colon <code>':'</code>. The "<code>c:\</code>" or "<code>\</code>" is called the root. Windows supports multiple roots, each maps to a drive (e.g., "<code>c:\</code>", "<code>d:\</code>"). Unix has single root ("<code>\</code>").
 A path could be absolute (beginning from the root) or relative (which 
is relative to the current working directory). Special notations "<code>.</code>" and "<code>..</code>" denote the current directory and the parent directory, respectively. </p>

<p>A <code>java.nio.file.Path</code> instance specifies the location of a file, or a directory, or a symbolic link. <code>Path</code> replaces <code>java.io.File</code> (of the standard I/O), which is less versatile and buggy.</p>

<h4> Helper class <span class="font-code">java.nio.file.Paths</span></h4>

<p>To create a <code>Path</code>, use the <code>static</code> method <code>get()</code> of the helper class <code>java.nio.file.Paths</code>. The helper class <code>Paths</code> contains exclusively <code>static</code> methods for creating <code>Path</code> objects. <code>Paths.get()</code> returns a <code>Path</code> object by converting a given path string or <code>URI</code>. </p>

<div><div id="highlighter_34204" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path get(String first, String... more)</code></div><div class="line number2 index1 alt1"><code class="java comments">//# This method accepts variable number of arguments (varargs).</code></div><div class="line number3 index2 alt2"><code class="java comments">// It converts a path string, or a sequence of strings that when joined form a path string, to a Path object.</code></div><div class="line number4 index3 alt1"><code class="java comments">// The location of the Path may or may not exist.&nbsp; </code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;</code>&nbsp;</div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path get(URI uri)</code></div><div class="line number7 index6 alt2"><code class="java comments">//# Converts the given URI to a Path object.</code></div></div></td></tr></tbody></table></div></div>

<p>For example,</p>

<div><div id="highlighter_318889" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">Path p1 = Paths.get(</code><code class="java string">"in.txt"</code><code class="java plain">);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# A file in current directory, relative</code></div><div class="line number2 index1 alt1"><code class="java plain">Path p2 = Paths.get(</code><code class="java string">"c:\\myproejct\\java\\Hello.java"</code><code class="java plain">);&nbsp; </code><code class="java comments">//# File, absolute, need escape sequence for '\'</code></div><div class="line number3 index2 alt2"><code class="java plain">Path p3 = Paths.get(</code><code class="java string">"/use/local"</code><code class="java plain">);&nbsp; </code><code class="java comments">//# A directory</code></div></div></td></tr></tbody></table></div></div>

<p>As the directory-separator is system dependent, for writing portable 
and more flexible program, it is recommended to use an existing <code>Path</code> instance as an anchor to resolve the filename, e.g.,</p>
<div><div id="highlighter_170061" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">Path dir = ...</code></div><div class="line number2 index1 alt1"><code class="java plain">Path file = dir.resolve(</code><code class="java string">"filename"</code><code class="java plain">);&nbsp; </code><code class="java comments">//# Joins the filename to the dirname with a directory-separator</code></div></div></td></tr></tbody></table></div></div>

<p>A <code>Path</code> can be broken down as root, level-0, level-1, .... The method <code>getNameCount()</code> returns the levels. The method <code>getName(i)</code> returns the name of level-i. For example,</p>

<div><div id="highlighter_849502" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.nio.file.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">PathInfo {</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Windows</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path path = Paths.get(</code><code class="java string">"D:\\myproject\\java\\test\\Hello.java"</code><code class="java plain">);</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Unix/Mac</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//#Path path = Paths.get("/myproject/java/test/Hello.java");</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print Path Info</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"toString:&nbsp;&nbsp;&nbsp; "</code> <code class="java plain">+ path.toString());&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# D:\myproject\java\test\Hello.java</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"getFileName: "</code> <code class="java plain">+ path.getFileName()); </code><code class="java comments">//# Hello.java</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"getParent: "</code> <code class="java plain">+ path.getParent());&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# D:\myproject\java\test</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"getRoot: "</code> <code class="java plain">+ path.getRoot());&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# D:\</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# root, level-0, level-1, ...</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">nameCount = path.getNameCount();</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"getNameCount: "</code> <code class="java plain">+ nameCount);&nbsp;&nbsp; </code><code class="java comments">//# 4</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; nameCount; i++) {</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"getName("</code> <code class="java plain">+ i + </code><code class="java string">"): "</code> <code class="java plain">+ path.getName(i)); </code><code class="java comments">//# (0)myproject, (1)java,</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 </code><code class="java comments">//# (2) test, (3) Hello.java</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"subpath(0,2): "</code> <code class="java plain">+ path.subpath(</code><code class="java value">0</code><code class="java plain">,</code><code class="java value">2</code><code class="java plain">));&nbsp; </code><code class="java comments">//# myproject\java</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"subpath(1,4): "</code> <code class="java plain">+ path.subpath(</code><code class="java value">1</code><code class="java plain">,</code><code class="java value">4</code><code class="java plain">));&nbsp; </code><code class="java comments">//# java\test\Hello.java</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number24 index23 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<h4>Helper Class <span class="font-code">java.nio.file.Files</span></h4>
<p>The class <code>Files</code> contains exclusively <code>static</code> methods for file, directory and symlink operations such as create, delete, read, write, copy, move, etc.</p>

<h5>Properties of a File/Directory</h5>

<p>You can use <code>static</code> <code>boolean</code> methods <code>Files.exists(Path)</code> and <code>File.notExists(Path)</code> to verify if a given <code>Path</code> exists or does not exist (as a file, directory or symlink). A <code>Path</code>
 could be verified to exist, or not exist, or unknown (e.g., the program
 does not have access to the file). If the status is unknown, the <code>exists()</code> and <code>noExists()</code> returns <code>false</code>.</p>
<p>You could also use <code>static</code> <code>boolean</code> methods <code>Files.isDirectory(Path)</code>, <code>Files.isRegularFile(Path)</code> and <code>Files.isSymbolicLink(Path)</code> to verify whether a <code>Path</code> locates a file, directory, or symlink.</p>
<p>Many of these  methods take an optional second argument of <code>LinkOption</code>, which is applicable for symlink only. For example, <code>LinkOption.NOFOLLOW_LINKS</code> specifies do not follow the symlink.</p>

<div><div id="highlighter_148701" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">long</code> <code class="java plain">size(Path path)&nbsp; </code><code class="java comments">//# Returns the size of the file</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">exists(Path path, LinkOption... options)</code></div><div class="line number4 index3 alt1"><code class="java comments">//# Verifies whether the given Path exists, as a file/directory/symlink.</code></div><div class="line number5 index4 alt2"><code class="java comments">// It returns false if the file does not exist or status is unknown.</code></div><div class="line number6 index5 alt1"><code class="java comments">// LinkOption specifies how symlink should be handled, </code></div><div class="line number7 index6 alt2"><code class="java comments">//&nbsp;&nbsp; e.g., NOFOLLOW_LINKS: Do not follow symlinks.</code></div><div class="line number8 index7 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">notExists(Path path, LinkOption... options)&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Not exists?</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number10 index9 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">isDirectory(Path path, LinkOption... options)&nbsp;&nbsp; </code><code class="java comments">//# a directory?</code></div><div class="line number11 index10 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">isRegularFile(Path path, LinkOption... options) </code><code class="java comments">//# a file?</code></div><div class="line number12 index11 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">isSymbolicLink(Path
 
path)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 </code><code class="java comments">//# a symblink?</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number14 index13 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">isReadable(Path path)&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# readable?</code></div><div class="line number15 index14 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">isWritable(Path path)&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# writable?</code></div><div class="line number16 index15 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">isExecutable(Path path)&nbsp; </code><code class="java comments">//# executable?</code></div></div></td></tr></tbody></table></div></div>

<p>For example, to get the size of a file in JDK 1.7:</p>
<div><div id="highlighter_464339" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# JDK 7: Use static method java.nio.file.Files.size(path)</code></div><div class="line number2 index1 alt1"><code class="java plain">Path path = Paths.get(</code><code class="java string">"test.jpg"</code><code class="java plain">);</code></div><div class="line number3 index2 alt2"><code class="java plain">System.out.println(</code><code class="java string">"Files.Size(): "</code> <code class="java plain">+ Files.size(path));</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code>&nbsp;</div><div class="line number5 index4 alt2"><code class="java comments">//# Pre-JDK 7: Use java.io.File method aFile.length()</code></div><div class="line number6 index5 alt1"><code class="java plain">File file = </code><code class="java keyword">new</code> <code class="java plain">File(</code><code class="java string">"test.jpg"</code><code class="java plain">);</code></div><div class="line number7 index6 alt2"><code class="java plain">System.out.println(</code><code class="java string">"File.length():"</code> <code class="java plain">+ file.length());</code></div></div></td></tr></tbody></table></div></div>

<h5>Deleting a File/Directory</h5>
<p>You can use <code>static</code> methods <code>delete(Path)</code> to delete a file or directory. Directory can be deleted only if it is empty. A <code>boolean</code> method <code>deleteIfExists()</code> is also available.</p>


<div><div id="highlighter_379452" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">delete(Path path) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">boolean</code> <code class="java plain">deleteIfExists(Path path) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<h5>Copying/Moving a File/Directory</h5>
<p>You can use <code>static</code> methods <code>copy(Path, Path, CopyOption)</code> or <code>move(Path, Path, CopyOption)</code> to copy or move a file or directory. The methods return the target <code>Path</code>.</p>

<p>The methods accepts an optional third argument of <code>CopyOption</code>. For examples: <code>CopyOption.REPLACE_EXISTING</code> replaces the target if it exists; <code>CopyOption.COPY_ATTRIBUTES</code> copies the file attributes such as the dates; <code>CopyOption.NOFOLLOW_LINKS</code> specifies not to follow symlinks.</p>

<div><div id="highlighter_634522" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path copy(Path source, Path target, CopyOption... options) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path move(Path source, Path target, CopyOption... options) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<p>To copy a file into another directory:</p>
<div><div id="highlighter_440783" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">Path source = ...</code></div><div class="line number2 index1 alt1"><code class="java plain">Path targetDir = ...</code></div><div class="line number3 index2 alt2"><code class="java plain">Files.copy(source, targetDir.resolve(source.getFileName());</code></div></div></td></tr></tbody></table></div></div>

<h5>Reading/Writing Small Files</h5>

<p>For small files, you can use <code>static</code> methods <code>Files.readAllBytes(Path)</code> (byte-based) and <code>Files.readAllLines(Path, Charset)</code> (character-based) to read the entire file. You can use <code>Files.write(Path, byte[])</code> (byte-based) or <code>Files.write(Path, Iterable, Charset)</code> (character-based) to write to a file.</p>
<p>The optional <code>OpenOption</code> includes: <code>WRITE</code>, <code>APPEND</code>, <code>TRUNCATE_EXISTING</code> (truncates the file to zero bytes), <code>CREATE_NEW</code> (creates a new file and throws an exception if the file already exists), <code>CREATE</code> (opens the file if it exists or creates a new file if it does not), among others.</p>

<h5>Byte-based Operation</h5>
<div><div id="highlighter_773032" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">byte</code><code class="java plain">[] readAllBytes(Path path) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java comments">//# Reads all bytes and returns a byte array. </code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path write(Path path, </code><code class="java keyword">byte</code><code class="java plain">[] bytes, OpenOption... options) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number4 index3 alt1"><code class="java comments">//# Default options are: CREATE, TRUNCATE_EXISTING, and WRITE</code></div></div></td></tr></tbody></table></div></div>
 
<h5>Character-based Operation</h5>
<div><div id="highlighter_2152" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">List&lt;String&gt; readAllLines(Path path, Charset cs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java comments">//# Reads all lines and returns a list of String.</code></div><div class="line number3 index2 alt2"><code class="java comments">// Line terminator could be "\n", "\r\n" or "\r".</code></div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path write(Path path, Iterable&lt;? </code><code class="java keyword">extends</code> <code class="java plain">CharSequence&gt; lines, </code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Charset cs, OpenOption... options) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<p><span class="line-heading">Examples: The following example write a 
small text file (in "UTF-8"), and read the entire file back as bytes as 
well as characters.</span></p>

<div><div id="highlighter_440988" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div><div class="line number39 index38 alt2">39</div><div class="line number40 index39 alt1">40</div><div class="line number41 index40 alt2">41</div><div class="line number42 index41 alt1">42</div><div class="line number43 index42 alt2">43</div><div class="line number44 index43 alt1">44</div><div class="line number45 index44 alt2">45</div><div class="line number46 index45 alt1">46</div><div class="line number47 index46 alt2">47</div><div class="line number48 index47 alt1">48</div><div class="line number49 index48 alt2">49</div><div class="line number50 index49 alt1">50</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.nio.file.*;</code></div><div class="line number3 index2 alt2"><code class="java keyword">import</code> <code class="java plain">java.nio.charset.*;</code></div><div class="line number4 index3 alt1"><code class="java keyword">import</code> <code class="java plain">java.util.*;</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">SmallFileIOJDK7 {</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String fileStr = </code><code class="java string">"small_file.txt"</code><code class="java plain">;</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path path = Paths.get(fileStr);</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Strings with unicode characters</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">List&lt;String&gt; lines = </code><code class="java keyword">new</code> <code class="java plain">ArrayList&lt;String&gt;();</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">lines.add(</code><code class="java string">"Hi,您好!"</code><code class="java plain">);</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">lines.add(</code><code class="java string">"Hello,吃饱了没有?"</code><code class="java plain">);</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write to text file in UTF-8</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Files.write(path, lines, Charset.forName(</code><code class="java string">"UTF-8"</code><code class="java plain">));</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read the whole file as bytes</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">byte</code><code class="java plain">[] bytes;</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">bytes = Files.readAllBytes(path);</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">byte</code> <code class="java plain">aByte: bytes) {</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, aByte);</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%n%n"</code><code class="java plain">);</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read the whole file as characters</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">List&lt;String&gt; inLines;</code></div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number38 index37 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">inLines = Files.readAllLines(path, Charset.forName(</code><code class="java string">"UTF-8"</code><code class="java plain">));</code></div><div class="line number39 index38 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(String aLine: inLines) {</code></div><div class="line number40 index39 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; aLine.length(); i++) {</code></div><div class="line number41 index40 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">char</code> <code class="java plain">charOut = aLine.charAt(i);</code></div><div class="line number42 index41 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"[%d]'%c'(%04X) "</code><code class="java plain">, (i+</code><code class="java value">1</code><code class="java plain">), charOut, (</code><code class="java keyword">int</code><code class="java plain">)charOut);</code></div><div class="line number43 index42 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number44 index43 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number45 index44 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number46 index45 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number47 index46 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number48 index47 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number49 index48 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number50 index49 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">48 69 2C <span class="underline">E6 82 A8 <span class="underline">E5 A5 BD 21 0D 0A
<span class="color-comment">H  i  ,  您       好       !  CR LF
48 65 6C 6C 6F 2C <span class="underline">E5 90 83 <span class="underline">E9 A5 B1 <span class="underline">E4 BA 86 <span class="underline">E6 B2 A1 <span class="underline">E6 9C 89 3F 0D 0A
<span class="color-comment">H  e  l  l  o  ,  吃       饱       了       没       有        ?  CR LF

[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)

[1]'H'(0048) [2]'e'(0065) [3]'l'(006C) [4]'l'(006C) [5]'o'(006F) [6]','(002C) 
[7]'吃'(5403) [8]'饱'(9971) [9]'了'(4E86) [10]'没'(6CA1) [11]'有'(6709) [12]'?'(003F)</span></span></span></span></span></span></span></span></span></pre>

<h5>Buffered Character-based I/O for Text Files</h5>
<p>For Reading, use <code>Files.newBufferedReader(Path, Charset)</code> method to open a text file, which returns a <code>BufferedReader</code>. Use <code>BufferedReader.readLine()</code> to read a line, <code>read()</code> to read a char, or <code>read(char[] cbuf, int off, int len)</code> to read into a char-array.</p>

<p>For Writing, use the <code>Files.newBufferedWriter(Path, Charset, OpenOption...)</code> method to open a output text  file, which returns a <code>BufferedWriter</code>. Use <code>BufferedWriter.write(int c)</code> to write a character, <code>write(char[] cbuf, int off, int len)</code> or <code>write(String s, int off, int len)</code> to write characters.</p>

<div><div id="highlighter_31899" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">BufferedReader newBufferedReader(Path path, Charset cs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;</code>&nbsp;</div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options)</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<h5>Byte-Based Stream I/O</h5>
<p>Use <code>Files.newInputStream(Path, OpenOption...)</code> to allocate an <code>InputStream</code> for reading raw bytes; and <code>Files.newOutputStream(Path, OpenOption...)</code> to allocate an <code>OutputStream</code> for writing. The <code>InputStream</code> and <code>OutputStream</code> returned are not buffered.</p>

<p><span class="line-heading">Example: Similar to the previous program which read/write the entire file, this program read/write via Buffered I/O.</span></p>
<div><div id="highlighter_220230" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div><div class="line number39 index38 alt2">39</div><div class="line number40 index39 alt1">40</div><div class="line number41 index40 alt2">41</div><div class="line number42 index41 alt1">42</div><div class="line number43 index42 alt2">43</div><div class="line number44 index43 alt1">44</div><div class="line number45 index44 alt2">45</div><div class="line number46 index45 alt1">46</div><div class="line number47 index46 alt2">47</div><div class="line number48 index47 alt1">48</div><div class="line number49 index48 alt2">49</div><div class="line number50 index49 alt1">50</div><div class="line number51 index50 alt2">51</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.nio.file.*;</code></div><div class="line number3 index2 alt2"><code class="java keyword">import</code> <code class="java plain">java.nio.charset.*;</code></div><div class="line number4 index3 alt1"><code class="java keyword">import</code> <code class="java plain">java.util.*;</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">BufferedFileIOJDK7 {</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String fileStr = </code><code class="java string">"buffered_file.txt"</code><code class="java plain">;</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path path = Paths.get(fileStr);</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Strings with unicode characters</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">List&lt;String&gt; lines = </code><code class="java keyword">new</code> <code class="java plain">ArrayList&lt;String&gt;();</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">lines.add(</code><code class="java string">"Hi,您好!"</code><code class="java plain">);</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">lines.add(</code><code class="java string">"Hello,吃饱了没有?"</code><code class="java plain">);</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Charset charset = Charset.forName(</code><code class="java string">"UTF-8"</code><code class="java plain">);</code></div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Write to text file (encoded in UTF-8)</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedWriter out = Files.newBufferedWriter(path, charset)) {</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(String line: lines) {</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">out.write(line, </code><code class="java value">0</code><code class="java plain">, line.length());</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read the file as bytes</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedInputStream in = </code><code class="java keyword">new</code> <code class="java plain">BufferedInputStream(Files.newInputStream(path))) {</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">int</code> <code class="java plain">inByte;</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((inByte = in.read()) != -</code><code class="java value">1</code><code class="java plain">) {</code></div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%02X "</code><code class="java plain">, inByte);</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"%n%n"</code><code class="java plain">);</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Read the file as characters</code></div><div class="line number38 index37 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String inLine;</code></div><div class="line number39 index38 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">(BufferedReader in = Files.newBufferedReader(path, charset)) {</code></div><div class="line number40 index39 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">while</code> <code class="java plain">((inLine = in.readLine()) != </code><code class="java keyword">null</code><code class="java plain">) {</code></div><div class="line number41 index40 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(</code><code class="java keyword">int</code> <code class="java plain">i = </code><code class="java value">0</code><code class="java plain">; i &lt; inLine.length(); i++) {</code></div><div class="line number42 index41 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">char</code> <code class="java plain">aChar = inLine.charAt(i);</code></div><div class="line number43 index42 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"[%d]'%c'(%04X) "</code><code class="java plain">, (i+</code><code class="java value">1</code><code class="java plain">), aChar, (</code><code class="java keyword">int</code><code class="java plain">)aChar);</code></div><div class="line number44 index43 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number45 index44 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println();</code></div><div class="line number46 index45 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number47 index46 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number48 index47 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number49 index48 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number50 index49 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number51 index50 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<pre class="output">48 69 2C <span class="underline">E6 82 A8 <span class="underline">E5 A5 BD 21
<span class="color-comment">H  i  ,  您       好       !
48 65 6C 6C 6F 2C <span class="underline">E5 90 83 <span class="underline">E9 A5 B1 <span class="underline">E4 BA 86 <span class="underline">E6 B2 A1 <span class="underline">E6 9C 89 3F
<span class="color-comment">H  e  l  l  o  ,  吃       饱       了       没       有        ?

[1]'H'(0048) [2]'i'(0069) [3]','(002C) [4]'您'(60A8) [5]'好'(597D) [6]'!'(0021)
[7]'H'(0048) [8]'e'(0065) [9]'l'(006C) [10]'l'(006C) [11]'o'(006F) [12]','(002C)
[13]'吃'(5403) [14]'饱'(9971) [15]'了'(4E86) [16]'没'(6CA1) [17]'有'(6709) [18]'?'(003F)</span></span></span></span></span></span></span></span></span></pre>


<h5>Creating a New File/Directory/Symlink</h5>
<p>Beside using the <code>Files.write()</code> method with <code>OpenOption</code> of <code>CREATE</code> or <code>CREATE_NEW</code>, you can also use <code>Files.createFile()</code>
 method to create an empty file. You can use the default file attributes
 or optionally define the initial attributes of the file.</p>

<div><div id="highlighter_796844" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path createFile(Path path, FileAttribute&lt;?&gt;... attrs)</code></div></div></td></tr></tbody></table></div></div>

<p>The <code>FileAttribute</code> includes: [TODO]</p>
<ul>
<li>DOS:</li>
<li>Unixes: Nine file permissions: read, write, and execute permissions 
for the file owner, members of the same group, and "everyone else", 
e.g., "<code>rwxr-x---</code>".</li>
</ul>

<p>Example: [TODO]</p>

<p>Similary, you can create a new directory, symlink as follows:</p>

<div><div id="highlighter_324183" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path createDirectory(Path dir, FileAttribute&lt;?&gt;... attrs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java comments">//# Creates a new directory.</code></div><div class="line number3 index2 alt2">&nbsp;</div><div class="line number4 index3 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path createDirectories(Path dir, FileAttribute&lt;?&gt;... attrs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number5 index4 alt2"><code class="java comments">//# Creates a directory by creating all nonexistent "parent" directories first</code></div><div class="line number6 index5 alt1">&nbsp;</div><div class="line number7 index6 alt2"><code class="java keyword">public</code> <code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path createSymbolicLink(Path link, Path target,</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">FileAttribute&lt;?&gt;... attrs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number9 index8 alt2"><code class="java comments">//# Creates a symbolic link to a target</code></div></div></td></tr></tbody></table></div></div>

<p>Example:</p>
<div><div id="highlighter_979658" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">Files.createDirectory(Paths.get(</code><code class="java string">"d:\\temp\\test"</code><code class="java plain">));</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# With default attribute</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# FileAlreadyExistsException if already exists</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">Files.createDirectory(Paths.get(</code><code class="java string">"d:\\temp\\test1\\test2"</code><code class="java plain">));</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# NoSuchFileException if parent does not exist</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">Files.createDirectories(Paths.get(</code><code class="java string">"d:\\temp\\test1\\test2"</code><code class="java plain">));</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Also create the parent directory</code></div><div class="line number9 index8 alt2"><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number11 index10 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<h5>Creating a Temporary File/Directory</h5>

<div><div id="highlighter_405953" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path createTempFile(Path dir, String prefix, String suffix,</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">FileAttribute&lt;?&gt;... attrs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number3 index2 alt2"><code class="java comments">//# Creates a new empty file in the specified dir, </code></div><div class="line number4 index3 alt1"><code class="java comments">//&nbsp; using the given prefix and suffix to generate its name.</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path createTempFile(String prefix, String suffix,</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">FileAttribute&lt;?&gt;... attrs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number8 index7 alt1"><code class="java comments">//# Creates an empty file in the default temporary-file directory, </code></div><div class="line number9 index8 alt2"><code class="java comments">//&nbsp; using the given prefix and suffix to generate its name.</code></div><div class="line number10 index9 alt1">&nbsp;</div><div class="line number11 index10 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path createTempDirectory(</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path dir, String prefix, FileAttribute&lt;?&gt;... attrs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code>&nbsp;</div><div class="line number14 index13 alt1"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path createTempDirectory(</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">String prefix, FileAttribute&lt;?&gt;... attrs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<p>Example: [TODO]</p>

<h4>File Attributes</h4>

<p>You can use one of the <code>Files.readAttributes()</code> methods to read all the basic attribute of a path.</p>

<div><div id="highlighter_506329" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Map&lt;String,Object&gt; readAttributes(</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path path, String attributes, LinkOption... options) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number3 index2 alt2"><code class="java comments">//# Read Reads a set of file attributes.</code></div><div class="line number4 index3 alt1">&nbsp;</div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Object getAttribute(</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path path, String attribute, LinkOption... options) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number7 index6 alt2"><code class="java comments">//# Get a given attribute</code></div><div class="line number8 index7 alt1">&nbsp;</div><div class="line number9 index8 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path setAttribute(</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path path, String attribute, Object value, LinkOption... options) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number11 index10 alt2"><code class="java comments">//# Set a given attribute</code></div></div></td></tr></tbody></table></div></div>

<h4>FileChannel</h4>

<div><div id="highlighter_631301" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">SeekableByteChannel newByteChannel(</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path path, OpenOption... options) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number3 index2 alt2"><code class="java comments">//# Opens or creates a file, returning a seekable byte channel to access the file.</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number5 index4 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">SeekableByteChannel newByteChannel(</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path path, Set&lt;? </code><code class="java keyword">extends</code> <code class="java plain">OpenOption&gt; options, FileAttribute&lt;?&gt;... attrs)</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number8 index7 alt1"><code class="java comments">//# Opens or creates a file, returning a seekable byte channel to access the file.</code></div></div></td></tr></tbody></table></div></div>

<h4>Random Access File</h4>

<p>The Interface <code>SeekableByteChannel</code> supports random access.</p>

<div><div id="highlighter_881367" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java plain">pubic </code><code class="java keyword">long</code> <code class="java plain">position()&nbsp;&nbsp; </code></div><div class="line number2 index1 alt1"><code class="java comments">//# Returns this channel's position.</code></div><div class="line number3 index2 alt2"><code class="java keyword">public</code> <code class="java plain">SeekableByteChannel position(</code><code class="java keyword">long</code> <code class="java plain">newPosition)&nbsp; </code></div><div class="line number4 index3 alt1"><code class="java comments">//# Sets this channel's position.</code></div><div class="line number5 index4 alt2">&nbsp;</div><div class="line number6 index5 alt1"><code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">read(ByteBuffer dest)&nbsp; </code></div><div class="line number7 index6 alt2"><code class="java comments">//# Reads a sequence of bytes from this channel into the given ByteBuffer.</code></div><div class="line number8 index7 alt1"><code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">write(ByteBuffer source)&nbsp; </code></div><div class="line number9 index8 alt2"><code class="java comments">//# Writes a sequence of bytes to this channel from the given ByteBuffer.</code></div><div class="line number10 index9 alt1">&nbsp;</div><div class="line number11 index10 alt2"><code class="java keyword">public</code> <code class="java keyword">long</code> <code class="java plain">size()</code></div><div class="line number12 index11 alt1"><code class="java comments">//# Returns the current size of entity to which this channel is connected.</code></div><div class="line number13 index12 alt2"><code class="java keyword">public</code> <code class="java plain">SeekableByteChannel truncate(</code><code class="java keyword">long</code> <code class="java plain">size)&nbsp; </code></div><div class="line number14 index13 alt1"><code class="java comments">//# Truncates the entity, to which this channel is connected, to the given size.</code></div></div></td></tr></tbody></table></div></div>


<h4>Directory Operations</h4>

<h5>List all root directories</h5>

<div><div id="highlighter_196838" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# Print the root directories for the default file system</code></div><div class="line number2 index1 alt1"><code class="java plain">Iterable&lt;Path&gt; rootDirs = FileSystems.getDefault().getRootDirectories();</code></div><div class="line number3 index2 alt2"><code class="java keyword">for</code> <code class="java plain">(Path rootDir : rootDirs) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(rootDir);</code></div><div class="line number5 index4 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>


<h5>Listing a directory</h5>
<p>You can list the contents of a directory by using the <code>Files.newDirectoryStream(Path)</code> method. The returned <code>DirectoryStream</code> object implements <code>Iterable</code>. You can interate thru the entries with for-each loop.</p>

<div><div id="highlighter_106474" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">DirectoryStream&lt;Path&gt; newDirectoryStream(Path dir) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

      
<p><span class="line-heading">Example: List the contents of a directory</span></p>

<div><div id="highlighter_638244" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# List the contents of a directory</code></div><div class="line number2 index1 alt1"><code class="java plain">Path dir = Paths.get(</code><code class="java string">"."</code><code class="java plain">);</code></div><div class="line number3 index2 alt2"><code class="java keyword">try</code> <code class="java plain">(DirectoryStream&lt;Path&gt; dirStream = Files.newDirectoryStream(dir)) {</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(Path entry : dirStream) {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(entry.getFileName());&nbsp; </code><code class="java comments">//# Filename only</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(entry.toString());&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Full-path name</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number8 index7 alt1"><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException | DirectoryIteratorException ex) {</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number10 index9 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<p>In addition, you can include a glob pattern to filter the entries.</p>

<div><div id="highlighter_633755" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">DirectoryStream&lt;Path&gt; newDirectoryStream(Path dir, String glob)</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>
      
<p><span class="line-heading">Example: List the contents of a directory filtered by a glob.</span></p>

<div><div id="highlighter_553140" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# List the contents of a directory filtered by a glob pattern</code></div><div class="line number2 index1 alt1"><code class="java plain">Path dir = Paths.get(</code><code class="java string">"."</code><code class="java plain">);</code></div><div class="line number3 index2 alt2"><code class="java keyword">try</code> <code class="java plain">(DirectoryStream&lt;Path&gt; dirStream</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">= Files.newDirectoryStream(dir, </code><code class="java string">"h*.{java,class,txt}"</code><code class="java plain">)) {</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# begins with 'h' and ends with .java or .class or .txt</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(Path entry : dirStream) {</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(entry.getFileName());&nbsp; </code><code class="java comments">//# Filename only</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(entry.toString());&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Full-path name</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number10 index9 alt1"><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number12 index11 alt1"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<h5>Glob</h5>
<p>A glob is a subset of regular expression.</p>
<ul>
<li><code>'*'</code> matches zero or more character (0+).</li>
<li><code>'?'</code> matches any one character.</li>
<li><code>'**'</code> behaves like <code>'*'</code>, but can cross directory boundary, for matching on full path.</li>
<li><code>{...,....,...}</code> encloses a set of sub-patterns separated by ','.</li>
<li><code>[...]</code> encloses a set of single character or a range of character with <code>'-'</code>, e.g., [aeiou], [a-z], [0-9].</li>
<li>Any other character matches itself. To match <code>'*'</code>, <code>'?'</code> or special characters, prefix with <code>'\'</code>.</li>
</ul>
<p>For example: "<code>h*.{java,class,txt}</code>" matches entry starts with "<code>h</code>" and ends with "<code>.java</code>", "<code>.class</code>", or "<code>.txt</code>".</p>

<p>You can also write your own codes to filter the entries.</p>
<div><div id="highlighter_442181" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">DirectoryStream&lt;Path&gt; newDirectoryStream(</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path dir, DirectoryStream.Filter&lt;? </code><code class="java keyword">super</code> <code class="java plain">Path&gt; filter) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<p>The interface <code>DirectoryStream.Filter&lt;T&gt;</code> declares one <code>abstract</code> <code>boolean</code> method <code>accept()</code>, which will be call-back for each entry. Those entries that resulted in false <code>accept()</code> will be discarded.</p>
<div><div id="highlighter_587398" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">accept(T entry) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<p><span class="line-heading">Example: The following program uses an anonymous instance of an anonymous <code>DirectoryStream.Filter</code> sub-class to filter the <code>DirectoryStream</code>. The call-back method <code>accept()</code> returns <code>true</code> for regular files, and discards the rest. Take note that this filtering criterion cannot be implemented in a glob-pattern.</span></p>

<div><div id="highlighter_781494" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java comments">//# List the contents of a directory with a custom filter</code></div><div class="line number2 index1 alt1"><code class="java plain">Path dir = Paths.get(</code><code class="java string">"d:\\temp"</code><code class="java plain">);</code></div><div class="line number3 index2 alt2"><code class="java keyword">try</code> <code class="java plain">(DirectoryStream&lt;Path&gt; dirStream = Files.newDirectoryStream(dir,</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">new</code> <code class="java plain">DirectoryStream.Filter&lt;Path&gt;() {&nbsp;&nbsp; </code><code class="java comments">//# anonymous inner class</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">boolean</code> <code class="java plain">accept(Path entry) </code><code class="java keyword">throws</code> <code class="java plain">IOException {</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">return</code> <code class="java plain">(Files.isRegularFile(entry));&nbsp; </code><code class="java comments">//# regular file only</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">})) {</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">for</code> <code class="java plain">(Path entry : dirStream) {</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(entry.getFileName());&nbsp; </code><code class="java comments">//# Filename only</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(entry.toString());&nbsp;&nbsp;&nbsp;&nbsp; </code><code class="java comments">//# Full-path name</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number13 index12 alt2"><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">ex.printStackTrace();</code></div><div class="line number15 index14 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<h4>Walking the File Tree - <span class="font-code">Files.walkFileTree()</span></h4>
<p>You can use <code>static</code> method <code>Files.walkFileTree()</code> ro recursively walk thru all the files from a starting directory. </p>

<p>First of all, you need to create an object that implements interface <code>FileVisitor&lt;? super Path&gt;</code>, which declares these <code>abstract</code> methods:</p>

<div><div id="highlighter_547000" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java plain">FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number2 index1 alt1"><code class="java comments">//# Invoked for a directory before entries in the directory are visited.</code></div><div class="line number3 index2 alt2"><code class="java comments">// If this method returns CONTINUE, then entries in the directory are visited. </code></div><div class="line number4 index3 alt1"><code class="java comments">// If this method returns SKIP_SUBTREE or SKIP_SIBLINGS then entries in the directory </code></div><div class="line number5 index4 alt2"><code class="java comments">//&nbsp;&nbsp; (and any descendants) will not be visited.</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number7 index6 alt2"><code class="java keyword">public</code> <code class="java plain">FileVisitResult postVisitDirectory(T dir, IOException ex) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number8 index7 alt1"><code class="java comments">//# Invoked for a directory after entries in the directory, and all of their descendants, </code></div><div class="line number9 index8 alt2"><code class="java comments">//&nbsp;&nbsp; have been visited. This method is also invoked when iteration of the directory </code></div><div class="line number10 index9 alt1"><code class="java comments">//&nbsp;&nbsp; completes prematurely (by a visitFile method returning SKIP_SIBLINGS, </code></div><div class="line number11 index10 alt2"><code class="java comments">//&nbsp;&nbsp; or an I/O error when iterating over the directory).</code></div><div class="line number12 index11 alt1">&nbsp;</div><div class="line number13 index12 alt2"><code class="java keyword">public</code> <code class="java plain">FileVisitResult visitFile(T file, BasicFileAttributes attrs) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number14 index13 alt1"><code class="java comments">//# Invoked for a file/symlink in a directory.</code></div><div class="line number15 index14 alt2">&nbsp;</div><div class="line number16 index15 alt1"><code class="java keyword">public</code> <code class="java plain">FileVisitResult visitFileFailed(T file, IOException ex) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div><div class="line number17 index16 alt2"><code class="java comments">//# Invoked for a file that could not be visited. This method is invoked </code></div><div class="line number18 index17 alt1"><code class="java comments">//&nbsp;&nbsp; if the file's attributes could not be read, the file is a directory </code></div><div class="line number19 index18 alt2"><code class="java comments">//&nbsp;&nbsp; that could not be opened, and other reasons.</code></div></div></td></tr></tbody></table></div></div>

<p>These methods return an <code>enum</code> of <code>FileVisitResult</code>, which could take values of <code>CONTINUE</code>, <code>TERMINATE</code>, <code>SKIP_SUBTREES</code>, <code>SKIP_SIBLINGS</code>.</p>
<p>Instead of implementing <code>FileVisitor</code> interface, you could also extend from superclass <code>SimpleFileVisitor</code>, and override the selected methods.</p>

<p>There are two versions of <code>walkFileTree()</code>. The first version take a starting directory and a <code>FileVisitor</code>, and transerve through all the levels, without following the symlinks.</p>

<div><div id="highlighter_597570" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path walkFileTree(Path startDir, FileVisitor&lt;? </code><code class="java keyword">super</code> <code class="java plain">Path&gt; visitor) </code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>

<p><span class="line-heading">Example:</span></p>

<div><div id="highlighter_410338" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div><div class="line number12 index11 alt1">12</div><div class="line number13 index12 alt2">13</div><div class="line number14 index13 alt1">14</div><div class="line number15 index14 alt2">15</div><div class="line number16 index15 alt1">16</div><div class="line number17 index16 alt2">17</div><div class="line number18 index17 alt1">18</div><div class="line number19 index18 alt2">19</div><div class="line number20 index19 alt1">20</div><div class="line number21 index20 alt2">21</div><div class="line number22 index21 alt1">22</div><div class="line number23 index22 alt2">23</div><div class="line number24 index23 alt1">24</div><div class="line number25 index24 alt2">25</div><div class="line number26 index25 alt1">26</div><div class="line number27 index26 alt2">27</div><div class="line number28 index27 alt1">28</div><div class="line number29 index28 alt2">29</div><div class="line number30 index29 alt1">30</div><div class="line number31 index30 alt2">31</div><div class="line number32 index31 alt1">32</div><div class="line number33 index32 alt2">33</div><div class="line number34 index33 alt1">34</div><div class="line number35 index34 alt2">35</div><div class="line number36 index35 alt1">36</div><div class="line number37 index36 alt2">37</div><div class="line number38 index37 alt1">38</div><div class="line number39 index38 alt2">39</div><div class="line number40 index39 alt1">40</div><div class="line number41 index40 alt2">41</div><div class="line number42 index41 alt1">42</div><div class="line number43 index42 alt2">43</div><div class="line number44 index43 alt1">44</div><div class="line number45 index44 alt2">45</div><div class="line number46 index45 alt1">46</div><div class="line number47 index46 alt2">47</div><div class="line number48 index47 alt1">48</div><div class="line number49 index48 alt2">49</div><div class="line number50 index49 alt1">50</div><div class="line number51 index50 alt2">51</div><div class="line number52 index51 alt1">52</div><div class="line number53 index52 alt2">53</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">import</code> <code class="java plain">java.util.EnumSet;</code></div><div class="line number2 index1 alt1"><code class="java keyword">import</code> <code class="java plain">java.io.*;</code></div><div class="line number3 index2 alt2"><code class="java keyword">import</code> <code class="java plain">java.nio.file.*;</code></div><div class="line number4 index3 alt1"><code class="java keyword">import</code> <code class="java plain">java.nio.file.attribute.*;</code></div><div class="line number5 index4 alt2"><code class="java keyword">import</code> <code class="java keyword">static</code> <code class="java plain">java.nio.file.FileVisitResult.*;</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number7 index6 alt2"><code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">WalkFileTreeTest </code><code class="java keyword">extends</code> <code class="java plain">SimpleFileVisitor&lt;Path&gt; {</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print the directory visited.</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java color1">@Override</code></div><div class="line number11 index10 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java plain">FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr) {</code></div><div class="line number12 index11 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"Begin Directory: %s%n"</code><code class="java plain">, dir);</code></div><div class="line number13 index12 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">return</code> <code class="java plain">CONTINUE;</code></div><div class="line number14 index13 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number15 index14 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number16 index15 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print information about each file/symlink visited.</code></div><div class="line number17 index16 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java color1">@Override</code></div><div class="line number18 index17 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java plain">FileVisitResult visitFile(Path file, BasicFileAttributes attr) {</code></div><div class="line number19 index18 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">if</code> <code class="java plain">(attr.isSymbolicLink()) {</code></div><div class="line number20 index19 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"Symbolic link: %s "</code><code class="java plain">, file);</code></div><div class="line number21 index20 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">else</code> <code class="java keyword">if</code> <code class="java plain">(attr.isRegularFile()) {</code></div><div class="line number22 index21 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"Regular file: %s "</code><code class="java plain">, file);</code></div><div class="line number23 index22 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">else</code> <code class="java plain">{</code></div><div class="line number24 index23 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"Other: %s "</code><code class="java plain">, file);</code></div><div class="line number25 index24 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number26 index25 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(</code><code class="java string">"("</code> <code class="java plain">+ attr.size() + </code><code class="java string">"bytes)"</code><code class="java plain">);</code></div><div class="line number27 index26 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">return</code> <code class="java plain">CONTINUE;</code></div><div class="line number28 index27 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number29 index28 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number30 index29 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# Print the directory visited.</code></div><div class="line number31 index30 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java color1">@Override</code></div><div class="line number32 index31 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java plain">FileVisitResult postVisitDirectory(Path dir, IOException ex) {</code></div><div class="line number33 index32 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.printf(</code><code class="java string">"End Directory: %s%n%n"</code><code class="java plain">, dir);</code></div><div class="line number34 index33 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">return</code> <code class="java plain">CONTINUE;</code></div><div class="line number35 index34 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number36 index35 alt1"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number37 index36 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# If there is an error accessing the file, print a message and continue.</code></div><div class="line number38 index37 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java color1">@Override</code></div><div class="line number39 index38 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java plain">FileVisitResult visitFileFailed(Path file, IOException ex) {</code></div><div class="line number40 index39 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.err.println(ex);</code></div><div class="line number41 index40 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">return</code> <code class="java plain">CONTINUE;&nbsp; </code><code class="java comments">//# or TERMINATE</code></div><div class="line number42 index41 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number43 index42 alt2"><code class="java spaces">&nbsp;</code>&nbsp;</div><div class="line number44 index43 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# main</code></div><div class="line number45 index44 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number46 index45 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number47 index46 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path startingDir = Paths.get(</code><code class="java string">".."</code><code class="java plain">);</code></div><div class="line number48 index47 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Files.walkFileTree(startingDir, </code><code class="java keyword">new</code> <code class="java plain">WalkFileTreeTest());</code></div><div class="line number49 index48 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number50 index49 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(ex);</code></div><div class="line number51 index50 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number52 index51 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number53 index52 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>

<p>The second version takes 2 additional arguments: the <code>options</code> specifies whether to follow symlink (e.g., <code>EnumSet.noneOf(FileVisitOption.class)</code> or <code>EnumSet.of(FileVisitOption.FOLLOW_LINKS)</code>); the <code>maxDepth</code> specifies the levels to visit (set to <code>Integer.MAX_VALUE</code> for all levels).</p>

<div><div id="highlighter_224110" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Path walkFileTree(</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path startDir, Set&lt;FileVisitOption&gt; options, </code><code class="java keyword">int</code> <code class="java plain">maxDepth, FileVisitor&lt;? </code><code class="java keyword">super</code> <code class="java plain">Path&gt; visitor)</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java keyword">throws</code> <code class="java plain">IOException</code></div></div></td></tr></tbody></table></div></div>
      
<p>For example, the following main() method can be used for the previous example.</p>

<div><div id="highlighter_454087" class="syntaxhighlighter  java"><div class="toolbar"><span><a href="#" class="toolbar_item command_help help">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div><div class="line number7 index6 alt2">7</div><div class="line number8 index7 alt1">8</div><div class="line number9 index8 alt2">9</div><div class="line number10 index9 alt1">10</div><div class="line number11 index10 alt2">11</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java keyword">void</code> <code class="java plain">main(String[] args) {</code></div><div class="line number2 index1 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java keyword">try</code> <code class="java plain">{</code></div><div class="line number3 index2 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Path startingDir = Paths.get(</code><code class="java string">".."</code><code class="java plain">);</code></div><div class="line number4 index3 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">EnumSet&lt;FileVisitOption&gt; opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);</code></div><div class="line number5 index4 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# or EnumSet.noneOf(FileVisitOption.class)</code></div><div class="line number6 index5 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">Files.walkFileTree(startingDir, opts, </code><code class="java value">2</code><code class="java plain">, </code><code class="java keyword">new</code> <code class="java plain">WalkFileTreeTest());</code></div><div class="line number7 index6 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java comments">//# use Integer.MAX_VALUE for all level</code></div><div class="line number8 index7 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">} </code><code class="java keyword">catch</code> <code class="java plain">(IOException ex) {</code></div><div class="line number9 index8 alt2"><code class="java spaces">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="java plain">System.out.println(ex);</code></div><div class="line number10 index9 alt1"><code class="java spaces">&nbsp;&nbsp;&nbsp;</code><code class="java plain">}</code></div><div class="line number11 index10 alt2"><code class="java plain">}</code></div></div></td></tr></tbody></table></div></div>


<h4>Watching the Directory for Changes - Interface <span class="font-code">java.nio.file.WatchService</span></h4>




</div>
</div>
</div>
		</div>
		<!-- ENDS MAIN -->

			<!-- FOOTER -->
			<div id="footer">
				
				<!-- Bottom -->
				<div id="bottom">
					2011-2013 <a href="https://plus.google.com/111999105737049483944/about" rel="author">AppKubos</a> (HTML5) All Rights Reserved
					<!--div id="to-top" class="poshytip" title="To top"></div-->

					
					
					
				</div>
				<!-- ENDS Bottom -->
			</div>
			
			<!-- ENDS FOOTER -->
		
		</div>
		<!-- ENDS WRAPPER -->
		</article>

<script type="text/javascript">
function textsizer(e){
var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
var actualkey=String.fromCharCode(unicode)
if (actualkey=="a")
document.body.style.fontSize="120%"
if (actualkey=="z")
document.body.style.fontSize="100%"
}
document.onkeypress=textsizer
</script>



<script>
$(document).ready(function(){

	// hide #back-top first
	$("#back-top-sq").hide();
	
	// fade in #back-top
	$(function () {
		$(window).scroll(function () {
			if ($(this).scrollTop() > 100) {
				$('#back-top-sq').fadeIn();
			} else {
				$('#back-top-sq').fadeOut();
			}
		});

		// scroll body to 0px on click
		$('#back-top-sq a').click(function () {
			$('body,html').animate({
				scrollTop: 0
			}, 800);
			return false;
		});
	});

});
</script>	
<style>

/*
Back to top button 
*/
#back-top-sq {
	position: fixed;
	bottom: 0px;
}
#back-top-sq a {
	width: 48px;
	display: block;
	text-align: center;
	text-transform: uppercase;
	text-decoration: none;
	color: #bbb;
	/* background color transition */
	-webkit-transition: 1s;
	-moz-transition: 1s;
	transition: 1s;
}
#back-top-sq a:hover {
	color: #000;
}
/* arrow icon (span tag) */
#back-top-sq span {
	width: 48px;
	height: 48px;
	display: block;
	margin-bottom: 7px;
	background: #000 url('/ajax2/img/to-top.png') no-repeat center center;
	/* rounded corners */
	-webkit-border-radius: 15px;
	-moz-border-radius: 15px;
	border-radius: 15px;
	/* background color transition */
	-webkit-transition: 1s;
	-moz-transition: 1s;
	transition: 1s;
}
#back-top-sq a:hover span {
	background-color: #333;
}
</style>
	<p style="display: block;" id="back-top-sq">
						<a href="#top"><span></span></a>
					</p>
 


<div id="fancybox-tmp"></div><div id="fancybox-loading"><div></div></div><div id="fancybox-overlay"></div><div id="fancybox-wrap"><div id="fancybox-outer"><div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div><div id="fancybox-content"></div><a id="fancybox-close"></a><div id="fancybox-title"></div><a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a><a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a></div></div></body></html>